List of usage examples for org.jfree.chart ChartUtilities saveChartAsPNG
public static void saveChartAsPNG(File file, JFreeChart chart, int width, int height) throws IOException
From source file:org.picketlink.idm.performance.TestBase.java
protected void generateGraph(String filename, String subDir) { (new File(graphBaseDir + "/" + subDir)).mkdirs(); XYSeries series = new XYSeries("XYGraph"); long sum = 0; for (Map.Entry<Integer, Number> entry : measure.entrySet()) { series.add(entry.getKey(), entry.getValue()); sum += (Long) entry.getValue(); }//w ww . j a va 2s . c om XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createXYLineChart(filename, // Title "# of users", // x-axis Label "time to create one" + " ... S:" + sum + ", " + "A: " + ((double) sum / measure.size()), // y-axis // Label dataset, // Dataset PlotOrientation.VERTICAL, // Plot Orientation false, // Show Legend false, // Use tooltips false // Configure chart to generate URLs? ); try { ChartUtilities.saveChartAsPNG(new File(graphBaseDir + "/" + subDir + "/" + filename + ".png"), chart, 1200, 800); } catch (IOException e) { System.err.println(e); System.err.println("Problem occurred creating chart."); } }
From source file:org.cytoscape.dyn.internal.graphMetrics.SaveChartDialog.java
@Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == cancelButton) { this.setVisible(false); this.dispose(); } else if (e.getSource() == saveChartButton) { JFileChooser saveFileDialog = new JFileChooser(); saveFileDialog/*w ww . j av a 2 s . c o m*/ .addChoosableFileFilter(new ExtensionFileFilter(".jpeg", ".jpg", "Jpeg images (.jpeg, .jpg)")); saveFileDialog.addChoosableFileFilter( new ExtensionFileFilter(".png", "Portable Network Graphic images (.png)")); saveFileDialog .addChoosableFileFilter(new ExtensionFileFilter(".svg", "Scalable Vector Graphics (.svg)")); int save = saveFileDialog.showSaveDialog(this); if (save == JFileChooser.APPROVE_OPTION) { File file = saveFileDialog.getSelectedFile(); int width = ((SpinnerNumberModel) widthSpinner.getModel()).getNumber().intValue(); int height = ((SpinnerNumberModel) heightSpinner.getModel()).getNumber().intValue(); ExtensionFileFilter filter = null; try { filter = (ExtensionFileFilter) saveFileDialog.getFileFilter(); if (!filter.hasExtension(file)) { file = filter.appendExtension(file); } } catch (ClassCastException ex) { // Try to infer the type of file by its extension FileFilter[] filters = saveFileDialog.getChoosableFileFilters(); for (int i = 0; i < filters.length; ++i) { if (filters[i] instanceof ExtensionFileFilter) { filter = (ExtensionFileFilter) filters[i]; if (filter.hasExtension(file)) { break; } filter = null; } } if (filter == null) { // Could not infer the type JOptionPane.showMessageDialog(null, "File type not specified!\nWhen giving file name, please also select one of the supported file types.", "Error", JOptionPane.ERROR_MESSAGE); return; } } // Save the chart to the specified file name try { String ext = filter.getExtension(); if (ext.equals("jpeg")) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (ext.equals("png")) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else { VectorGraphics graphics = new SVGGraphics2D(file, new Dimension(width, height)); graphics.startExport(); chart.draw(graphics, new Rectangle2D.Double(0, 0, width, height)); graphics.endExport(); } } catch (IOException ex) { JOptionPane.showMessageDialog(null, "An error occurred while creating or writing to the file.", "Error", JOptionPane.ERROR_MESSAGE); return; } this.setVisible(false); this.dispose(); } else if (save == JFileChooser.ERROR_OPTION) { JOptionPane.showMessageDialog(null, "An error occurred while initializing the window.", "Error", JOptionPane.ERROR_MESSAGE); } } }
From source file:com.comcast.cmb.test.tools.QueueDepthSimulator.java
public static void scatterPlot(Map<String, List<Double>> datasets, String filename, String title, String labelX, String labelY) throws IOException { XYSeriesCollection dataset = new XYSeriesCollection(); for (String label : datasets.keySet()) { XYSeries data = new XYSeries(label); int cnt = 0; for (Double d : datasets.get(label)) { data.add(cnt, d);/*from w w w .j a v a2s . co m*/ cnt++; } dataset.addSeries(data); } JFreeChart chart = ChartFactory.createScatterPlot(title, labelX, labelY, dataset, PlotOrientation.VERTICAL, true, true, false); ChartUtilities.saveChartAsPNG(new File(filename), chart, 1024, 768); }
From source file:org.objectweb.proactive.extensions.timitspmd.util.charts.HierarchicalBarChart.java
private void buildFinalChart(String title, String subTitle, String xAxisLabel, String yAxisLabel, int height, int width, String filename, Chart.Scale scaleMode, Chart.LegendFormat legendFormatMode, int alpha) { @SuppressWarnings("unchecked") Vector<Counter>[] vec = new Vector[this.timers.length]; boolean exist; // create the dataset... for (int i = 0; i < this.timers.length; i++) { vec[i] = new Vector<Counter>(); @SuppressWarnings("unchecked") Iterator<Element> it = this.timers[i].getDescendants(); while (it.hasNext()) { try { Element elt = (Element) it.next(); String name = elt.getAttributeValue("name"); double value = Double.valueOf(elt.getAttributeValue("avg")); exist = false;//w w w . jav a 2s. c o m for (int j = 0; j < vec[i].size(); j++) { if (((Counter) vec[i].get(j)).getName().equals(name)) { ((Counter) vec[i].get(j)).addValue(value); exist = true; break; } } if (!exist) { vec[i].add(new Counter(name, value)); } } catch (ClassCastException e) { continue; } } } CategoryDataset dataset = null; try { dataset = DatasetUtilities.createCategoryDataset(toSeries(vec[0]), this.categories, toDataset(vec)); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new IllegalArgumentException( "Benchmark names must have different names. Be sure that your filter contains correct timers names"); } // create the chart... final CategoryAxis categoryAxis = new CategoryAxis(xAxisLabel); final ValueAxis valueAxis = new NumberAxis(yAxisLabel); final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, new HierarchicalBarRenderer()); plot.setOrientation(PlotOrientation.VERTICAL); final JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true); chart.addSubtitle(new TextTitle(subTitle)); // set the background color for the chart... chart.setBackgroundPaint(Color.white); final HierarchicalBarRenderer renderer = (HierarchicalBarRenderer) plot.getRenderer(); renderer.setItemMargin(0.01); renderer.setDatasetTree(this.timers); renderer.setSeries(toSeries(vec[0])); renderer.setAlpha(alpha); final CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryMargin(HierarchicalBarChart.CATEGORY_MARGIN); domainAxis.setUpperMargin(0.05); domainAxis.setLowerMargin(0.05); try { if ((filename == null) || "".equals(filename)) { throw new RuntimeException( "The output filename for the HierarchicalBarChart cannot be null or empty !"); } ChartUtilities.saveChartAsPNG(XMLHelper.createFileWithDirs(filename + ".png"), chart, width, height); Utilities.saveChartAsSVG(chart, new Rectangle(width, height), XMLHelper.createFileWithDirs(filename + ".svg")); } catch (java.io.IOException e) { System.err.println("Error writing chart image to file"); e.printStackTrace(); } }
From source file:tmn.dev.project.Player.java
/** * Generate a plot of batting average over the span of a season and write * the plot to a PNG file.//from ww w. ja v a 2 s . c o m * * @return The String representation of the name of the PNG file containing * the plot. * @throws IOException */ private String createBAPlot() throws IOException { // Create a scatter plot for batting average over the season // Game number on the x axis, Batting average on the y axis JFreeChart chart = ChartFactory.createScatterPlot("Batting Average Throughout the Season", "Game Number", "Batting Average", new XYSeriesCollection(baGame), PlotOrientation.VERTICAL, false, false, false); XYPlot plot = chart.getXYPlot(); // Set the axis ranges to provide an appropriate zoom NumberAxis xAxis = (NumberAxis) plot.getDomainAxis(); xAxis.setRange(baGame.getMinX(), baGame.getMaxX()); NumberAxis yAxis = (NumberAxis) plot.getRangeAxis(); yAxis.setRange(baGame.getMinY() - .02, baGame.getMaxY() + .02); // Set the tick labels on the y axis to the typical BA format yAxis.setNumberFormatOverride(new DecimalFormat(".000")); // Create the String representation of the /images directory String imgDirStr = System.getProperty("user.dir") + System.getProperty("file.separator") + "images"; // If the directory doesn't already exist, create it File imgDir = new File(imgDirStr); if (!imgDir.exists() && !imgDir.isDirectory()) imgDir.mkdir(); // Create the batting average PNG files String fileName = imgDirStr + System.getProperty("file.separator") + this.getId() + ".png"; File imgFile = new File(fileName); // If the file already exists, append a number in parentheses int index = 0; while (!imgFile.createNewFile()) { // Append (<index>).html after the Player ID fileName = imgDirStr + System.getProperty("file.separator") + this.getId() + "(" + ++index + ")" + ".png"; // Try to create a file with this name imgFile = new File(fileName); } // Write the plot to the PNG file that was created ChartUtilities.saveChartAsPNG(imgFile, chart, 800, 450); return imgFile.getName(); }
From source file:org.spantus.exp.segment.draw.AbstractGraphGenerator.java
protected void draw(JFreeChart chart, String name, Double widthCoef, Double heightCoef) { Double width = 800 * widthCoef; Double height = 270 * heightCoef; try {/* w ww . j a va 2 s. c om*/ new File(getGeneratePath()).mkdirs(); String _name = name.replaceAll(":", "_"); _name = _name.replaceAll("^\\s+", "").replaceAll("\\s+$", "").replaceAll("\\s+", "-"); ChartUtilities.saveChartAsPNG(new File(getGeneratePath() + _name + ".png"), chart, width.intValue(), height.intValue()); } catch (IOException e) { e.printStackTrace(); } }
From source file:playground.johannes.snowball.Histogram.java
public void plot(String filename, String title) throws IOException { fillBins();/* w ww.j av a 2s.co m*/ final XYSeriesCollection data = new XYSeriesCollection(); final XYSeries wave = new XYSeries(title, false, true); double min, max, width; // int size; if (bounds != null) { min = bounds[0]; max = bounds[1]; } else { double minmax[] = getMinMax(); min = minmax[0]; max = minmax[1]; } if (binWidth > 0) { // size = (int)Math.ceil((max - min)/(double)binWidth); width = binWidth; } else { // size = bincount; width = (max - min) / (double) bincount; } int cnt = bins.size(); for (int i = 0; i < cnt; i++) { wave.add(i * width + min, bins.get(i)); } data.addSeries(wave); final JFreeChart chart = ChartFactory.createXYStepChart("title", "x", "y", data, PlotOrientation.VERTICAL, true, // legend false, // tooltips false // urls ); XYPlot plot = chart.getXYPlot(); final CategoryAxis axis1 = new CategoryAxis("x"); axis1.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 7)); plot.setDomainAxis(new NumberAxis("y")); ChartUtilities.saveChartAsPNG(new File(filename), chart, 1024, 768); }
From source file:org.miloss.fgsms.services.rs.impl.reports.os.FreeDiskSpace.java
@Override public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files, TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx) throws IOException { Connection con = Utility.getPerformanceDBConnection(); try {//from w w w .j a va2 s.co m PreparedStatement cmd = null; ResultSet rs = null; JFreeChart chart = null; data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>"); data.append(GetHtmlFormattedHelp() + "<br />"); data.append( "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Send Rate</th><th>Average Free Disk Space (all paritions)</th><th>Average Write KB/s</th><th>Average Read KB/s</th></tr>"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) { continue; } String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i))); double average = 0; data.append("<tr><td>").append(url).append("</td>"); try { cmd = con.prepareStatement( "select avg(freespace) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(average + "").append("</td>"); try { cmd = con.prepareStatement( "select avg(writekbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); average = 0; if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(average + "").append("</td>"); try { cmd = con.prepareStatement( "select avg(readkbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); average = 0; if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(average + "").append("</td></tr>"); //ok now get the raw data.... TimeSeriesContainer tsc = new TimeSeriesContainer(); try { cmd = con.prepareStatement( "select readkbs, writekbs,freespace, utcdatetime, driveidentifier from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); while (rs.next()) { TimeSeries ts2 = tsc.Get(url + " " + rs.getString("driveidentifier"), Millisecond.class); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(rs.getLong(4)); Millisecond m = new Millisecond(gcal.getTime()); ts2.addOrUpdate(m, rs.getLong("freespace")); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } for (int ik = 0; ik < tsc.data.size(); ik++) { col.addSeries(tsc.data.get(ik)); } } data.append("</table>"); chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "MBytes", col, true, false, false); try { // if (set.getRowCount() != 0) { ChartUtilities.saveChartAsPNG(new File( path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, 400); data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">"); files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"); // } } catch (IOException ex) { log.log(Level.ERROR, "Error saving chart image for request", ex); } } catch (Exception ex) { log.log(Level.ERROR, null, ex); } finally { DBUtils.safeClose(con); } }
From source file:name.martingeisse.reporting.renderer.HtmlRenderer.java
/** * @param chartBlock/* w w w . j av a 2 s.c o m*/ */ private void render(ChartBlock chartBlock) { File imageFile = allocateResource("chart-$.png"); out.print("<div><img src=\"" + imageFile.getName() + "\" /></div>"); try { ChartUtilities.saveChartAsPNG(imageFile, chartBlock.getChart(), 1000, 600); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.miloss.fgsms.services.rs.impl.reports.os.DiskIOReport.java
@Override public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files, TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx) throws IOException { Connection con = Utility.getPerformanceDBConnection(); try {//from ww w .j a v a 2 s . co m PreparedStatement cmd = null; ResultSet rs = null; JFreeChart chart = null; data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>"); data.append(GetHtmlFormattedHelp() + "<br />"); data.append( "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Free Disk Space (all paritions)</th><th>Average Write KB/s</th><th>Average Read KB/s</th></tr>"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) { continue; } String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i))); double average = 0; data.append("<tr><td>").append(url).append("</td>"); try { cmd = con.prepareStatement( "select avg(freespace) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(average + "").append("</td>"); average = 0; try { cmd = con.prepareStatement( "select avg(writekbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(average + "").append("</td>"); average = 0; try { cmd = con.prepareStatement( "select avg(readkbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(average + "").append("</td></tr>"); //ok now get the raw data.... TimeSeriesContainer tsc = new TimeSeriesContainer(); try { cmd = con.prepareStatement( "select readkbs, writekbs,freespace, utcdatetime, driveidentifier from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); while (rs.next()) { TimeSeries ts = tsc.Get(url + " " + rs.getString("driveidentifier") + " Read", Millisecond.class); TimeSeries ts2 = tsc.Get(url + " " + rs.getString("driveidentifier") + " Write", Millisecond.class); //TimeSeries ts2 = tsc.Get(urls.get(i) + " " + rs.getString("driveidentifier") , Millisecond.class); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(rs.getLong(4)); Millisecond m = new Millisecond(gcal.getTime()); ts.addOrUpdate(m, rs.getLong("readKBs")); ts2.addOrUpdate(m, rs.getLong("writeKBs")); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } for (int ik = 0; ik < tsc.data.size(); ik++) { col.addSeries(tsc.data.get(ik)); } } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Rate", col, true, false, false); data.append("</table>"); try { // if (set.getRowCount() != 0) { ChartUtilities.saveChartAsPNG(new File( path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, 400); data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">"); files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"); // } } catch (IOException ex) { log.log(Level.ERROR, "Error saving chart image for request", ex); } } catch (Exception ex) { log.log(Level.ERROR, null, ex); } finally { DBUtils.safeClose(con); } }