public void drawChart(String filename, int width, int height) throws IOException { // Create plot NumberAxis xAxis = new NumberAxis(xAxisLabel); NumberAxis yAxis = new NumberAxis(yAxisLabel); XYSplineRenderer renderer = new XYSplineRenderer(); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(4, 4, 4, 4)); // Create chart JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, true); ChartUtilities.applyCurrentTheme(chart); ChartPanel chartPanel = new ChartPanel(chart, false); // Draw png BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics graphics = bi.getGraphics(); chartPanel.setBounds(0, 0, width, height); chartPanel.paint(graphics); ImageIO.write(bi, "png", new File(filename)); }
public static void writeROCCurves(File outputFile, TreeMap<String, HitStatistic> hits) throws Exception{ XYSeriesCollection dataset = new XYSeriesCollection(); for(Entry<String, HitStatistic> e:hits.entrySet()){ File txtFile=new File(outputFile.getAbsolutePath().replaceAll(".jpg","_"+e.getKey().split("-")[2]+".txt")); BufferedWriter bw=new BufferedWriter(new FileWriter(txtFile)); XYSeries series= new XYSeries(e.getKey()); bw.write("false positive rate\tsensitivity"); bw.newLine(); List<double[]> roc=e.getValue().getROCAverage(); for(double[] r:roc){ bw.write(r[0]+"\t"+r[1]); bw.newLine(); series.add(r[0],r[1]); } dataset.addSeries(series); bw.close(); } final JFreeChart chart =ChartFactory.createXYLineChart("ROCCurve", "false positive rate", "sensitivity", dataset); ChartUtilities.saveChartAsJPEG(outputFile, chart, 1000, 400); }
public static void writeRankVSScore(File outputFile, List<SimilarityMatrix> matrices, int length, String add) throws Exception{ final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset(); for(SimilarityMatrix m:matrices){ int[][] sortedIndizes=m.getIndizesOfSortedScores(); List<Double>[] scoreList=new List[Math.min(length,sortedIndizes[0].length)]; for(int i=0;i<scoreList.length;i++)scoreList[i]=new ArrayList<Double>(); for(int i=0;i<sortedIndizes.length;i++){ int l=0; for(int j=0;j<sortedIndizes[i].length;j++){ double v=m.getSimilarityValue(i,sortedIndizes[i][j]); if(!Double.isNaN(v)){ scoreList[l].add(v); l++; } if(l>=scoreList.length)break; } } for(int i=0;i<scoreList.length;i++) dataset.add(scoreList[i], m.getMethodsQueryAndDBString(), i); } JFreeChart chart=ChartFactory.createBoxAndWhiskerChart("Whiskerplot", "Ranks", "Scores", dataset, true); ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+sep+add+"RankVSScore_"+getMethodsQueryStringFromList(matrices)+".jpg"), chart, Math.min(2000,length*100), 1000); }
/** * Opens a file chooser and gives the user an opportunity to save the chart in PNG format. * * @throws IOException * if there is an I/O error. */ @Override public void doSaveAs() throws IOException { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs); ExtensionFileFilter filter = new ExtensionFileFilter(localizationResources.getString("PNG_Image_Files"), ".png"); fileChooser.addChoosableFileFilter(filter); int option = fileChooser.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION) { String filename = fileChooser.getSelectedFile().getPath(); if (isEnforceFileExtensions()) { if (!filename.endsWith(".png")) { filename = filename + ".png"; } } ChartUtilities.saveChartAsPNG(new File(filename), this.chart, getWidth(), getHeight()); } }
public void actionPerformed(ActionEvent e) { try{ if(fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION){ String SelectedFileName = fileChooser.getSelectedFile().getAbsolutePath(); if(SelectedFileName.toUpperCase().endsWith(".JPG")|| SelectedFileName.toUpperCase().endsWith(".JPEG")){ ChartUtilities.saveChartAsJPEG(new File(SelectedFileName),TEdit,500,500); return; } if(SelectedFileName.toUpperCase().endsWith(".PNG")){ ChartUtilities.saveChartAsPNG(new File(SelectedFileName),TEdit,500,500); return; } ChartUtilities.saveChartAsPNG(new File(SelectedFileName+".png"),TEdit,500,500); } } catch(Exception Ex){ System.out.println(Ex.toString()); } }
/** * {@inheritDoc} */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<PollOption> results = null; try { Long pollId = (Long) req.getSession().getAttribute("pollID"); results = DAOProvider.getDao().getPollOptions(pollId); } catch (Exception ex) { results = new ArrayList<>(); } JFreeChart chart = DBUtility.getChart(results); ChartUtilities.writeChartAsPNG(resp.getOutputStream(), chart, 700, 400); }
/** * {@inheritDoc} */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String resultFile = req.getServletContext().getRealPath( "/WEB-INF/glasanje-rezultati.txt"); String definitionFile = req.getServletContext().getRealPath( "/WEB-INF/glasanje-definicija.txt"); List<Band> results = ServerUtilty .getResults(definitionFile, resultFile); JFreeChart chart = ServerUtilty.getChart(results); ChartUtilities.writeChartAsPNG(resp.getOutputStream(), chart, 700, 400); resp.getOutputStream().flush(); }
/** * Saves the chart as a PNG format file in the temporary directory and * populates the ChartRenderingInfo object which can be used to generate * an HTML image map. * * @param chart the chart to be saved (<code>null</code> not permitted). * @param width the width of the chart. * @param height the height of the chart. * @param info the ChartRenderingInfo object to be populated (<code>null</code> permitted). * @param session the HttpSession of the client. * * @return the filename of the chart saved in the temporary directory. * * @throws IOException if there is a problem saving the file. */ public static String saveChartAsPNG(JFreeChart chart, int width, int height, ChartRenderingInfo info, HttpSession session) throws IOException { if (chart == null) { throw new IllegalArgumentException("Null 'chart' argument."); } ServletUtilities.createTempDir(); File tempFile = File.createTempFile( ServletUtilities.tempFilePrefix, ".png", new File(System.getProperty("java.io.tmpdir")) ); ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info); ServletUtilities.registerChartForDeletion(tempFile, session); return tempFile.getName(); }
/** * Saves the chart as a JPEG format file in the temporary directory and * populates the ChartRenderingInfo object which can be used to generate * an HTML image map. * * @param chart the chart to be saved (<code>null</code> not permitted). * @param width the width of the chart * @param height the height of the chart * @param info the ChartRenderingInfo object to be populated * @param session the HttpSession of the client * * @return the filename of the chart saved in the temporary directory * * @throws IOException if there is a problem saving the file. */ public static String saveChartAsJPEG(JFreeChart chart, int width, int height, ChartRenderingInfo info, HttpSession session) throws IOException { if (chart == null) { throw new IllegalArgumentException("Null 'chart' argument."); } ServletUtilities.createTempDir(); File tempFile = File.createTempFile( ServletUtilities.tempFilePrefix, ".jpeg", new File(System.getProperty("java.io.tmpdir")) ); ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info); ServletUtilities.registerChartForDeletion(tempFile, session); return tempFile.getName(); }
/** * Opens a file chooser and gives the user an opportunity to save the chart * in PNG format. * * @throws IOException if there is an I/O error. */ public void doSaveAs() throws IOException { FileDialog fileDialog = new FileDialog(canvas.getShell(), SWT.SAVE); String[] extensions = { "*.png" }; fileDialog.setFilterExtensions(extensions); String filename = fileDialog.open(); if (filename != null) { if (isEnforceFileExtensions()) { if (!filename.endsWith(".png")) { filename = filename + ".png"; } } //TODO replace getSize by getBounds ? ChartUtilities.saveChartAsPNG(new File(filename), this.chart, canvas.getSize().x, canvas.getSize().y); } }
/** * Saves the chart as a PNG format file in the temporary directory and * populates the {@link ChartRenderingInfo} object which can be used to * generate an HTML image map. * * @param chart the chart to be saved (<code>null</code> not permitted). * @param width the width of the chart. * @param height the height of the chart. * @param info the ChartRenderingInfo object to be populated * (<code>null</code> permitted). * @param session the HttpSession of the client (if <code>null</code>, the * temporary file is marked as "one-time" and deleted by * the {@link DisplayChart} servlet right after it is * streamed to the client). * * @return The filename of the chart saved in the temporary directory. * * @throws IOException if there is a problem saving the file. */ public static String saveChartAsPNG(JFreeChart chart, int width, int height, ChartRenderingInfo info, HttpSession session) throws IOException { if (chart == null) { throw new IllegalArgumentException("Null 'chart' argument."); } ServletUtilities.createTempDir(); String prefix = ServletUtilities.tempFilePrefix; if (session == null) { prefix = ServletUtilities.tempOneTimeFilePrefix; } File tempFile = File.createTempFile(prefix, ".png", new File(System.getProperty("java.io.tmpdir"))); ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info); if (session != null) { ServletUtilities.registerChartForDeletion(tempFile, session); } return tempFile.getName(); }
private void GenerateRTMapPNG(XYSeriesCollection xySeriesCollection, XYSeries series, float R2) throws IOException { new File(Workfolder + "/RT_Mapping/").mkdir(); String pngfile = Workfolder + "/RT_Mapping/" + FilenameUtils.getBaseName(LCMSA.mzXMLFileName).substring(0, Math.min(120, FilenameUtils.getBaseName(LCMSA.mzXMLFileName).length() - 1)) + "_" + FilenameUtils.getBaseName(LCMSB.mzXMLFileName).substring(0, Math.min(120, FilenameUtils.getBaseName(LCMSB.mzXMLFileName).length() - 1)) + "_RT.png"; XYSeries smoothline = new XYSeries("RT fitting curve"); for (XYZData data : regression.PredictYList) { smoothline.add(data.getX(), data.getY()); } xySeriesCollection.addSeries(smoothline); xySeriesCollection.addSeries(series); JFreeChart chart = ChartFactory.createScatterPlot("Retention time mapping: R2=" + R2, "RT:" + FilenameUtils.getBaseName(LCMSA.mzXMLFileName), "RT:" + FilenameUtils.getBaseName(LCMSB.mzXMLFileName), xySeriesCollection, PlotOrientation.VERTICAL, true, true, false); XYPlot xyPlot = (XYPlot) chart.getPlot(); xyPlot.setDomainCrosshairVisible(true); xyPlot.setRangeCrosshairVisible(true); XYItemRenderer renderer = xyPlot.getRenderer(); renderer.setSeriesPaint(1, Color.blue); renderer.setSeriesPaint(0, Color.BLACK); renderer.setSeriesShape(1, new Ellipse2D.Double(0, 0, 3, 3)); renderer.setSeriesStroke(1, new BasicStroke(3.0f)); renderer.setSeriesStroke(0, new BasicStroke(3.0f)); xyPlot.setBackgroundPaint(Color.white); ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600); }
/** * Opens a file chooser and gives the user an opportunity to save the chart * in PNG format. * * @throws IOException if there is an I/O error. */ public void doSaveAs() throws IOException { FileDialog fileDialog = new FileDialog(this.canvas.getShell(), SWT.SAVE); String[] extensions = {"*.png"}; fileDialog.setFilterExtensions(extensions); String filename = fileDialog.open(); if (filename != null) { if (isEnforceFileExtensions()) { if (!filename.endsWith(".png")) { filename = filename + ".png"; } } //TODO replace getSize by getBounds ? ChartUtilities.saveChartAsPNG(new File(filename), this.chart, this.canvas.getSize().x, this.canvas.getSize().y); } }
static String writeJChartToFile(JFreeChart chart, File file, FileTypes fileType) throws IOException, DocumentException { String fileName = file.getPath(); switch (fileType) { case svg: Tools.exportChartAsSVG(chart, new Rectangle(1000, 1000), file); break; case pdf: Tools.exportChartAsPDF(chart, new Rectangle(500, 400), file); break; case jchart: break; case csv: Tools.exportChartAsCSV(chart, file); break; default: ChartUtilities.saveChartAsPNG(file, chart, 1000, 1000); break; } return fileName; }
/** * Generates and writes the plotpipeline's clickable map to the response output * stream. * * @param req * the incoming request * @param rsp * the response stream * @throws IOException */ public void plotGraphMap(StaplerRequest req, StaplerResponse rsp) throws IOException { if ( ChartUtil.awtProblemCause != null) { // not available. send out error message rsp.sendRedirect2(req.getContextPath() + "/images/headless.png"); return; } setWidth(req); setHeight(req); setNumBuilds(req); setRightBuildNum(req); setHasLegend(req); setTitle(req); setStyle(req); setUseDescr(req); generatePlot(false); ChartRenderingInfo info = new ChartRenderingInfo(); plot.createBufferedImage(getWidth(), getHeight(), info); rsp.setContentType("text/plain;charset=UTF-8"); rsp.getWriter().println( ChartUtilities.getImageMap(getCsvFileName(), info)); }
private static JFreeChart createChart() { final CategoryAxis domainAxis = new CategoryAxis(""); final NumberAxis rangeAxis = new NumberAxis(""); final IntervalBarRenderer renderer = new IntervalBarRenderer(); renderer.setBaseToolTipGenerator(new IntervalCategoryToolTipGenerator()); renderer.setBaseToolTipGenerator((dataset, row, column) -> { final IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset; return icd.getRowKey(row) + ": " + (icd.getEndValue(row, column).doubleValue() - icd.getStartValue(row, column).doubleValue()); }); final CategoryPlot plot = new CategoryPlot(null, domainAxis, rangeAxis, renderer); final JFreeChart chart = new JFreeChart("Unternehmenswert", plot); plot.setDomainGridlinesVisible(true); plot.setRangePannable(true); ChartUtilities.applyCurrentTheme(chart); return chart; }
public void buildPlot1() { setColorLimits(); dataset = new DefaultValueDataset(30); ThermometerPlot thermometerplot = new ThermometerPlot(dataset); thermometerplot.setRange(plotBottonLimit, plotTopLimit); thermometerplot.setUnits(ThermometerPlot.UNITS_CELCIUS); thermometerplot.setSubrange(0, greenBottomLimit, greenTopLimit); thermometerplot.setSubrangePaint(0, Color.green); thermometerplot.setSubrange(1, yellowBottomLimit, yellowTopLimit); thermometerplot.setSubrangePaint(1, Color.yellow); thermometerplot.setSubrange(2, redBottomLimit, redTopLimit); thermometerplot.setSubrangePaint(2, Color.red); JFreeChart jfreechart = new JFreeChart(plotTitle, thermometerplot); ChartUtilities.applyCurrentTheme(jfreechart); add(new ChartPanel(jfreechart)); }
private static void buildChart(File mOutputFile, InformationCriterion ic) { /* This line prevents Swing exceptions on headless environments */ if (GraphicsEnvironment.isHeadless()) { return; } int width = 500; int height = 300; try { if (!IMAGES_DIR.exists()) { IMAGES_DIR.mkdir(); } ChartUtilities.saveChartAsPNG(new File(IMAGES_DIR.getPath() + File.separator + mOutputFile.getName() + "_rf_" + ic + ".png"), RFHistogram.buildRFHistogram(ic), width, height); ChartUtilities.saveChartAsPNG(new File(IMAGES_DIR.getPath() + File.separator + mOutputFile.getName() + "_eu_" + ic + ".png"), RFHistogram.buildEuclideanHistogram(ic), width, height); } catch (IOException e) { // e.printStackTrace(); } }
private void salvarJPEG() { JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(new File(".jpg")); int returnVal = chooser.showSaveDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); try { ChartUtilities.saveChartAsJPEG(file, chartPanel.getChart(), chartPanel.getWidth(), chartPanel.getHeight()); } catch (IOException ex) { ex.printStackTrace(); } } }
public String getChartMap(String chartMapId) throws IOException { StringWriter writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); try { ChartUtilities.writeImageMap(pw, chartMapId, chartRenderingInfo, new StandardToolTipTagFragmentGenerator(), new StandardURLTagFragmentGenerator()); } finally { IOUtil.closeQuietly(pw); } return writer.toString(); }
/** * <p>getChartMap.</p> * * @param chartMapId a {@link java.lang.String} object. * @return a {@link java.lang.String} object. * @throws java.io.IOException if any. */ public String getChartMap(String chartMapId) throws IOException { StringWriter writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); try { ChartUtilities.writeImageMap(pw, chartMapId, chartRenderingInfo, new StandardToolTipTagFragmentGenerator(), new StandardURLTagFragmentGenerator()); } finally { IOUtil.closeQuietly(pw); } return writer.toString(); }
/** * * @return JPEG version of chart */ public byte[] getBytes() { try { JFreeChart chart = createChart(); ByteArrayOutputStream chartOut = new ByteArrayOutputStream(this.byteArrayBufferSize); ChartUtilities.writeChartAsJPEG(chartOut, chart, width, height); return chartOut.toByteArray(); } catch (IOException e) { throw new SystemException(Debugger.stackTrace(e)); } }
public void jpgLineChartTerminationRate(Integer percentTerminations[], List<Float> reliabilities) throws IOException { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (int j = 0; j < reliabilities.size(); j++) { dataset.addValue(percentTerminations[j], "early termination rate", reliabilities.get(j)); } JFreeChart lineChartObject = ChartFactory.createLineChart( "Percent early termination rate of reliability estimation", "Reliability Lower Bound (Slb)", "Percent early termination rate", dataset, PlotOrientation.VERTICAL, true, true, false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ String fileName = "earlyTerminationRate.jpeg"; File lineChart = new File(fileName); ChartUtilities.saveChartAsJPEG(lineChart, lineChartObject, width, height); logger.debug(fileName + " created"); }
public void jpgLineChartCostPRE(BigDecimal[] relativeErrors, List<Float> reliabilities) throws IOException { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (int j = 0; j < reliabilities.size(); j++) { dataset.addValue(relativeErrors[j], "", reliabilities.get(j)); } JFreeChart lineChartObject = ChartFactory.createLineChart( "Percent relative error of CostEstimation", "Reliability Lower Bound (Slb)", "Percent relative Error", dataset, PlotOrientation.VERTICAL, true, true, false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ String fileName = "costRelativeError.jpeg"; File lineChart = new File(fileName); ChartUtilities.saveChartAsJPEG(lineChart, lineChartObject, width, height); logger.debug(fileName + " created"); }
public void savePlots(String path)throws IOException{ File dir = new File(path); if(!dir.exists()) dir.mkdirs(); //Will Save in a way that an OS will list them in selected order but omits the TCC // int index=1; // for(String s : names){ // JFreeChart c = charts.get(s); // String n = "a"+index+"-"+s; // ChartUtilities.saveChartAsJPEG(new File(dir.getAbsolutePath()+"/"+n+".jpg"), c, width, height); // index++; // } for(String s : charts.keySet()){ JFreeChart c = charts.get(s); ChartUtilities.saveChartAsJPEG(new File(dir.getAbsolutePath()+"/"+s+".jpg"), c, width, height); } }
private void setupChart() { this.data = new TimeSeries("Counts"); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(this.data); DateAxis domain = new DateAxis("Time"); domain.setAutoRange(true); NumberAxis range = new NumberAxis("Count"); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setBaseShapesVisible(false); renderer.setBaseSeriesVisibleInLegend(false); XYPlot plot = new XYPlot(dataset, domain, range, renderer); this.chart = new JFreeChart("Mongo Counts", plot); ChartUtilities.applyCurrentTheme(this.chart); }
/** * Controller that handles the chart generation for a question statistics * @param surveyDefinitionId * @param pageOrder * @param questionOrder * @param recordCount * @param response */ @Secured({"ROLE_ADMIN","ROLE_SURVEY_ADMIN"}) @RequestMapping(value="/chart/{surveyDefinitionId}/{questionId}") public void generatePieChart(@PathVariable("surveyDefinitionId") Long surveyDefinitionId, @PathVariable("questionId") Long questionId, HttpServletResponse response) { try { response.setContentType("image/png"); long recordCount = surveyService.surveyStatistic_get(surveyDefinitionId).getSubmittedCount(); PieDataset pieDataSet= createDataset(questionId,recordCount); JFreeChart chart = createChart(pieDataSet, ""); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 340 ,200); response.getOutputStream().close(); } catch (Exception e) { log.error(e.getMessage(),e); throw (new RuntimeException(e)); } }
public static void generate(ClusterTimeSeriesReport report, String reportDir, String fileName) throws IOException { File root = new File(reportDir); if (!root.exists()) { if (!root.mkdirs()) { log.warn("Could not create root dir : " + root.getAbsolutePath() + " This might result in reports not being generated"); } else { log.info("Created root file: " + root); } } File chartFile = new File(root, fileName + ".png"); Utils.backupFile(chartFile); ChartUtilities.saveChartAsPNG(chartFile, createChart(report), 1024, 768); log.info("Chart saved as " + chartFile); }
public void generateChart(String dir) throws Exception { long nrReads = 0; long nrWrites = 0; if(reportDesc.getItems().size() > 0) { for (ReportItem item : reportDesc.getItems()) { getData.addValue(item.getReadsPerSec(), item.description(), "GET"); nrReads += item.getNoReads(); putData.addValue(item.getWritesPerSec(), item.description(), "PUT"); nrWrites += item.getNoWrites(); } File localGetFile = new File(dir, "local_gets_" + reportDesc.getReportName() + ".png"); Utils.backupFile(localGetFile); ChartUtilities.saveChartAsPNG(localGetFile, createChart("Report: Comparing Cache GET (READ) performance", getData, (int) (nrReads / reportDesc.getItems().size()), "(GETS)"), 800, 800); File localPutFile = new File(dir, "local_puts_" + reportDesc.getReportName() + ".png"); Utils.backupFile(localPutFile); ChartUtilities.saveChartAsPNG(localPutFile, createChart("Report: Comparing Cache PUT (WRITE) performance", putData, (int) (nrWrites / reportDesc.getItems().size()), "(PUTS)"), 800, 800); } }
private static void generateChart(String benchmark, DefaultCategoryDataset dataset, int benchmarkCount) { JFreeChart chart = ChartFactory.createBarChart( benchmark, "framework", "throughput", dataset, PlotOrientation.HORIZONTAL, true, false, false); CategoryPlot plot = chart.getCategoryPlot(); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setItemMargin(0); notSoUglyPlease(chart); String pngFile = getOutputName(benchmark); try { int height = 100 + benchmarkCount * 20; ChartUtilities.saveChartAsPNG(new File(pngFile), chart, 700, height); } catch (IOException e) { throw new RuntimeException(e); } }