// --- GET GROWTH GRAPHS ----------------------------------------------------------------------- protected PdfPTable getGrowthGraphs() throws Exception { PdfPTable growthTable = new PdfPTable(1); growthTable.setWidthPercentage(pageWidth); // *** height graph **************************************************** ByteArrayOutputStream osHeight = new ByteArrayOutputStream(); ChartUtilities.writeChartAsPNG(osHeight, getHeightGraph(), 680, 350); // put image in cell cell = new PdfPCell(); cell.setImage(com.itextpdf.text.Image.getInstance(osHeight.toByteArray())); cell.setBorder(PdfPCell.NO_BORDER); cell.setPaddingRight(10); growthTable.addCell(cell); // spacer growthTable.addCell(createBorderlessCell("", 30, 1)); // *** weight graph **************************************************** ByteArrayOutputStream osWeight = new ByteArrayOutputStream(); ChartUtilities.writeChartAsPNG(osWeight, getWeightGraph(), 680, 350); // put image in cell cell = new PdfPCell(); cell.setImage(com.itextpdf.text.Image.getInstance(osWeight.toByteArray())); cell.setBorder(PdfPCell.NO_BORDER); cell.setPaddingRight(10); growthTable.addCell(cell); return growthTable; }
protected void saveImage(String type) { // TODO 3 Image size should be dependent on the system graphics or configurable int height = 793; int width = 1120; AdvancedFileChooser fileChooser = new AdvancedFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = fileChooser.showSaveDialog(chartPanel); File filePath = null; if (returnVal == JFileChooser.APPROVE_OPTION) { filePath = fileChooser.getSelectedFile(); } String tempPath = filePath.getAbsolutePath().toUpperCase(); try { if (type.equals("PNG")) { if (!tempPath.endsWith(".PNG")) filePath = new File(tempPath + ".PNG"); ChartUtilities.saveChartAsPNG(filePath, getChart(), width, height); } else if (type.equals("JPEG")) { if (!tempPath.endsWith(".JPEG")) filePath = new File(tempPath + ".JPEG"); ChartUtilities.saveChartAsJPEG(filePath, getChart(), width, height); } } catch (IOException ie) { } }
private static JFreeChart createChart(CategoryDataset paramCategoryDataset) { JFreeChart localJFreeChart = ChartFactory.createAreaChart( "Area Chart", "Category", "Value", paramCategoryDataset, PlotOrientation.VERTICAL, true, true, false); localJFreeChart.setBackgroundPaint(Color.white); TextTitle localTextTitle = new TextTitle( "An area chart demonstration. We use this subtitle as an example of what happens when you get a really long title or subtitle."); localTextTitle.setPosition(RectangleEdge.TOP); localTextTitle.setPadding(new RectangleInsets(UnitType.RELATIVE, 0.05D, 0.05D, 0.05D, 0.05D)); localTextTitle.setVerticalAlignment(VerticalAlignment.BOTTOM); localJFreeChart.addSubtitle(localTextTitle); CategoryPlot localCategoryPlot = (CategoryPlot) localJFreeChart.getPlot(); localCategoryPlot.setForegroundAlpha(0.5F); localCategoryPlot.setDomainGridlinesVisible(true); CategoryAxis localCategoryAxis = localCategoryPlot.getDomainAxis(); localCategoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); localCategoryAxis.setLowerMargin(0.0D); localCategoryAxis.setUpperMargin(0.0D); localCategoryAxis.addCategoryLabelToolTip("Type 1", "The first type."); localCategoryAxis.addCategoryLabelToolTip("Type 2", "The second type."); localCategoryAxis.addCategoryLabelToolTip("Type 3", "The third type."); NumberAxis localNumberAxis = (NumberAxis) localCategoryPlot.getRangeAxis(); localNumberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); localNumberAxis.setLabelAngle(0.0D); ChartUtilities.applyCurrentTheme(localJFreeChart); return localJFreeChart; }
public void onSimulationComplete() { // TODO Auto-generated method stub this.removeAll(); synchronized (this) { chartPanel = newChart(data); } this.setLayout(new BorderLayout()); add(chartPanel, (new BorderLayout()).CENTER); chartPanel.updateUI(); File file; try { file = new File(outputpath); } catch (Exception e) { System.err.println("Graph Plugin " + label + " : Invalid output path" + e); return; } try { int width = 1920; int height = 1200; ChartUtilities.saveChartAsPNG(file, chartPanel.getChart(), width, height); } catch (Exception e) { System.out.println("Problem occurred creating chart." + label); } }
/** * Writes a graphic showing the number of departures, arrivals and vehicles en route of all * legs/trips with the specified transportation mode to the specified file. * * @param filename * @param legMode * @see #getGraphic(String) */ public void writeGraphic(final String filename, final String legMode) { try { ChartUtilities.saveChartAsPNG(new File(filename), getGraphic(legMode), 1024, 768); } catch (IOException e) { e.printStackTrace(); } }
private static JFreeChart finishBarChart(JFreeChart chart, Color... colors) { CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); categoryplot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT); categoryplot.setRangePannable(true); if (colors.length > 0) categoryplot.setRenderer(new CustomRenderer(colors)); BarRenderer barrenderer = (BarRenderer) categoryplot.getRenderer(); barrenderer.setItemLabelAnchorOffset(9D); barrenderer.setBaseItemLabelsVisible(true); barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); barrenderer.setMaximumBarWidth(0.05); barrenderer.setItemMargin(0.03D); ItemLabelPosition itemlabelposition = new ItemLabelPosition(INSIDE12, CENTER_RIGHT, CENTER_RIGHT, -1.5707963267948966D); barrenderer.setBasePositiveItemLabelPosition(itemlabelposition); ItemLabelPosition itemlabelposition1 = new ItemLabelPosition(OUTSIDE12, CENTER_LEFT, CENTER_LEFT, -1.5707963267948966D); barrenderer.setPositiveItemLabelPositionFallback(itemlabelposition1); CategoryAxis categoryaxis = categoryplot.getDomainAxis(); categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45); categoryaxis.setCategoryMargin(0.25D); categoryaxis.setUpperMargin(0.02D); categoryaxis.setLowerMargin(0.02D); NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); numberaxis.setUpperMargin(0.10000000000000001D); ChartUtilities.applyCurrentTheme(chart); return chart; }
public static void main(String[] args) throws IOException { JFreeChart chart = ChartFactory.createBarChart3D( "图书销量统计图", "图书", // 目录轴的显示标签 "销量", // 数值轴的显示标签 getDataSet(), PlotOrientation.VERTICAL, // 设置图表方向 false, false, false); // 设置标题 chart.setTitle(new TextTitle("图书销量统计图", new Font("黑体", Font.ITALIC, 22))); // 设置图表部分 CategoryPlot plot = (CategoryPlot) chart.getPlot(); CategoryAxis categoryAxis = plot.getDomainAxis(); // 取得横轴 categoryAxis.setLabelFont(new Font("宋体", Font.BOLD, 22)); // 设置横轴显示标签的字体 categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 分类标签以45度倾斜 categoryAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 18)); // 分类标签字体 NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis(); // 取得纵轴 numberAxis.setLabelFont(new Font("宋体", Font.BOLD, 42)); // 设置纵轴显示标签字体 FileOutputStream fos = null; fos = new FileOutputStream("book1.jpg"); ChartUtilities.writeChartAsJPEG(fos, 1, chart, 800, 600, null); fos.close(); }
private static JFreeChart createChart(PieDataset paramPieDataset) { JFreeChart localJFreeChart = ChartFactory.createPieChart("Legend Wrapper Demo 1", paramPieDataset, false, true, false); PiePlot localPiePlot = (PiePlot) localJFreeChart.getPlot(); localPiePlot.setLabelFont(new Font("SansSerif", 0, 12)); localPiePlot.setNoDataMessage("No data available"); localPiePlot.setCircular(true); localPiePlot.setLabelGap(0.02D); LegendTitle localLegendTitle = new LegendTitle(localJFreeChart.getPlot()); BlockContainer localBlockContainer1 = new BlockContainer(new BorderArrangement()); localBlockContainer1.setFrame(new BlockBorder(1.0D, 1.0D, 1.0D, 1.0D)); LabelBlock localLabelBlock1 = new LabelBlock("Legend Items:", new Font("SansSerif", 1, 12)); localLabelBlock1.setPadding(5.0D, 5.0D, 5.0D, 5.0D); localBlockContainer1.add(localLabelBlock1, RectangleEdge.TOP); LabelBlock localLabelBlock2 = new LabelBlock("Source: http://www.jfree.org"); localLabelBlock2.setPadding(8.0D, 20.0D, 2.0D, 5.0D); localBlockContainer1.add(localLabelBlock2, RectangleEdge.BOTTOM); BlockContainer localBlockContainer2 = localLegendTitle.getItemContainer(); localBlockContainer2.setPadding(2.0D, 10.0D, 5.0D, 2.0D); localBlockContainer1.add(localBlockContainer2); localLegendTitle.setWrapper(localBlockContainer1); localLegendTitle.setPosition(RectangleEdge.RIGHT); localLegendTitle.setHorizontalAlignment(HorizontalAlignment.LEFT); localJFreeChart.addSubtitle(localLegendTitle); ChartUtilities.applyCurrentTheme(localJFreeChart); return localJFreeChart; }
public void saveAsFile(String outputPath) { FileOutputStream out = null; try { File outFile = new File(outputPath); if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdirs(); } out = new FileOutputStream(outputPath); // 保存为PNG ChartUtilities.writeChartAsPNG(out, jfc, 800, 600); // 保存为JPEG // ChartUtilities.writeChartAsJPEG(out, chart, 500, 400); out.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // do nothing } } } }
private static JFreeChart createChart() { DateAxis dateaxis = new DateAxis("Date"); dateaxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); NumberAxis numberaxis = new NumberAxis("Value"); IntervalXYDataset intervalxydataset = createDataset1(); XYBarRenderer xybarrenderer = new XYBarRenderer(0.20000000000000001D); xybarrenderer.setBaseToolTipGenerator( new StandardXYToolTipGenerator( "{0}: ({1}, {2})", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00"))); XYPlot xyplot = new XYPlot(intervalxydataset, dateaxis, numberaxis, xybarrenderer); NumberAxis numberaxis1 = new NumberAxis("Value 2"); xyplot.setRangeAxis(1, numberaxis1); XYDataset xydataset = createDataset2A(); StandardXYItemRenderer standardxyitemrenderer = new StandardXYItemRenderer(); standardxyitemrenderer.setBaseToolTipGenerator( new StandardXYToolTipGenerator( "{0}: ({1}, {2})", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00"))); xyplot.setDataset(1, xydataset); xyplot.setRenderer(1, standardxyitemrenderer); XYDataset xydataset1 = createDataset2B(); xyplot.setDataset(2, xydataset1); xyplot.setRenderer(2, new StandardXYItemRenderer()); xyplot.mapDatasetToRangeAxis(2, 1); xyplot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); xyplot.setOrientation(PlotOrientation.VERTICAL); JFreeChart jfreechart = new JFreeChart("Overlaid XYPlot Demo 2", JFreeChart.DEFAULT_TITLE_FONT, xyplot, true); ChartUtilities.applyCurrentTheme(jfreechart); return jfreechart; }
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); } }
public static void generateHistogram( String fileName, double[] value, int numberOfBins, String title, String xLabel, String yLabel) { HistogramDataset dataset = new HistogramDataset(); dataset.setType(HistogramType.FREQUENCY); dataset.addSeries(title, value, numberOfBins); String plotTitle = title; String xaxis = xLabel; String yaxis = yLabel; PlotOrientation orientation = PlotOrientation.VERTICAL; boolean show = false; boolean toolTips = false; boolean urls = false; JFreeChart chart = ChartFactory.createHistogram( plotTitle, xaxis, yaxis, dataset, orientation, show, toolTips, urls); int width = 500; int height = 300; try { ChartUtilities.saveChartAsPNG(new File(fileName), chart, width, height); } catch (IOException e) { } }
/* * Metodo que aplica o filtro */ public static void Apply(BufferedImage image, String savePath) { // Chamada do metodo que gera os dados do histograma GetData(image); // Dataset que gera o grafico DefaultCategoryDataset ds = new DefaultCategoryDataset(); // Loop que percorre o array de dados do histograma for (int k = 0; k < data.length; k++) { // Adiciona o valor ao dataset ds.setValue(data[k], "Imagem", Integer.toString(data[k])); } // Gera o grafico JFreeChart grafico = ChartFactory.createLineChart( "Histograma", "Tons de cinza", "Valor", ds, PlotOrientation.VERTICAL, true, true, false); // Salva o grafico em um arquivo de png try { OutputStream arquivo = new FileOutputStream(savePath); ChartUtilities.writeChartAsPNG(arquivo, grafico, 550, 400); arquivo.close(); } catch (IOException e) { e.printStackTrace(); } }
private void writeChart(final String outFile, final JFreeChart chart) { try { ChartUtilities.saveChartAsPNG(new File(outFile), chart, 650, 455); } catch (IOException e) { e.printStackTrace(); } }
public static void drawPic(String url, String file) throws FileNotFoundException, IOException { // XYSeries xyseries = getXY(url); XYSeries xyseries = getXYseries(url); XYSeriesCollection xyseriescollection = new XYSeriesCollection(); // 再用XYSeriesCollection添加入XYSeries // 对象 xyseriescollection.addSeries(xyseries); // 创建主题样式 StandardChartTheme standardChartTheme = new StandardChartTheme("CN"); // 设置标题字体 standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20)); // 设置图例的字体 standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15)); // 设置轴向的字体 standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15)); // 应用主题样式 ChartFactory.setChartTheme(standardChartTheme); // JFreeChart chart=ChartFactory.createXYAreaChart("xyPoit", "点的标号", // "出现次数", xyseriescollection, PlotOrientation.VERTICAL, true, false, // false); JFreeChart chart = ChartFactory.createScatterPlot( "决策图", "点密度", "点距离", xyseriescollection, PlotOrientation.VERTICAL, true, false, false); // String file="d:/decision_chart.png"; try { ChartUtilities.saveChartAsPNG(new File(file), chart, 470, 470); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(new java.util.Date() + ": finished drawing the pic in " + file); }
/** * Creates a chart. * * @return A chart. */ private static JFreeChart createChart() { CategoryDataset dataset1 = createDataset1(); NumberAxis rangeAxis1 = new NumberAxis("Value"); rangeAxis1.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); LineAndShapeRenderer renderer1 = new LineAndShapeRenderer(); renderer1.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); CategoryPlot subplot1 = new CategoryPlot(dataset1, null, rangeAxis1, renderer1); subplot1.setDomainGridlinesVisible(true); CategoryDataset dataset2 = createDataset2(); NumberAxis rangeAxis2 = new NumberAxis("Value"); rangeAxis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); BarRenderer renderer2 = new BarRenderer(); renderer2.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); CategoryPlot subplot2 = new CategoryPlot(dataset2, null, rangeAxis2, renderer2); subplot2.setDomainGridlinesVisible(true); CategoryAxis domainAxis = new CategoryAxis("Category"); CombinedDomainCategoryPlot plot = new CombinedDomainCategoryPlot(domainAxis); plot.add(subplot1, 2); plot.add(subplot2, 1); JFreeChart chart = new JFreeChart( "Combined Domain Category Plot Demo", new Font("SansSerif", Font.BOLD, 12), plot, true); ChartUtilities.applyCurrentTheme(chart); return chart; }
/** * @param response * @param type * @param alphaList * @param title * @param xTitle * @param yTitle */ protected void createChart( final CollStatInfo csi, final Vector<Pair<String, Integer>> list, final String xTitle, final String yTitle) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Pair<String, Integer> p : list) { dataset.addValue(p.second, p.first, ""); } // if (StringUtils.isEmpty(csi.getInstName())) // { // csi.setInstName(getProviderNameFromInstCode(csi.getProviderId())); // } JFreeChart chart = ChartFactory.createBarChart( csi.getTitle(), xTitle, yTitle, dataset, PlotOrientation.VERTICAL, true, true, false); // chart.getCategoryPlot().setRenderer(new CustomColorBarChartRenderer()); chart.setBackgroundPaint(new Color(228, 243, 255)); try { Integer hashCode = csi.hashCode(); csi.setChartFileName(hashCode + ".png"); DataOutputStream dos = new DataOutputStream( new FileOutputStream(new File("reports/charts/" + csi.getChartFileName()))); ChartUtilities.writeChartAsPNG(dos, chart, 700, 600); } catch (Exception ex) { ex.printStackTrace(); } }
private void scatterPlot( Map<Double, Map<String, Tuple<Double, Double>>> inputData, String outFile) { String mode1 = travelModes[0]; String mode2 = travelModes[1]; XYSeries carFlow = new XYSeries(mode1 + " flow"); XYSeries bikeFlow = new XYSeries(mode2 + " flow"); XYSeries carSpeed = new XYSeries(mode1 + " speed"); XYSeries bikeSpeed = new XYSeries(mode2 + " speed"); for (double d : inputData.keySet()) { carFlow.add(d, inputData.get(d).get(mode1).getFirst()); carSpeed.add(d, inputData.get(d).get(mode1).getSecond()); bikeFlow.add(d, inputData.get(d).get(mode2).getFirst()); bikeSpeed.add(d, inputData.get(d).get(mode2).getSecond()); } // flow vs density XYSeriesCollection flowDataset = new XYSeriesCollection(); flowDataset.addSeries(carFlow); flowDataset.addSeries(bikeFlow); NumberAxis flowAxis = new NumberAxis("Flow (PCU/h)"); flowAxis.setRange(0.0, 2100.0); XYPlot plot1 = new XYPlot(flowDataset, null, flowAxis, new XYLineAndShapeRenderer(false, true)); plot1.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT); // speed vs density XYSeriesCollection speedDataset = new XYSeriesCollection(); speedDataset.addSeries(carSpeed); speedDataset.addSeries(bikeSpeed); NumberAxis speedAxis = new NumberAxis("Speed (m/s)"); speedAxis.setRange(0.0, 17.0); XYPlot plot2 = new XYPlot(speedDataset, null, speedAxis, new XYLineAndShapeRenderer(false, true)); plot2.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT); NumberAxis densityAxis = new NumberAxis("Overall density (PCU/km)"); densityAxis.setRange(0.0, 150.00); CombinedDomainXYPlot plot = new CombinedDomainXYPlot(densityAxis); plot.setGap(10.); plot.add(plot1); plot.add(plot2); plot.setOrientation(PlotOrientation.VERTICAL); JFreeChart chart = new JFreeChart("Fundamental diagrams", JFreeChart.DEFAULT_TITLE_FONT, plot, true); try { ChartUtilities.saveChartAsPNG(new File(outFile), chart, 800, 600); } catch (IOException e) { throw new RuntimeException("Data is not plotted. Reason " + e); } }
public static void main(String[] args) throws Exception { DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset(); line_chart_dataset.addValue(15, "schools", "1970"); line_chart_dataset.addValue(30, "schools", "1980"); line_chart_dataset.addValue(60, "schools", "1990"); line_chart_dataset.addValue(120, "schools", "2000"); line_chart_dataset.addValue(240, "schools", "2010"); line_chart_dataset.addValue(300, "schools", "2014"); JFreeChart lineChartObject = ChartFactory.createLineChart( "Schools Vs Years", "Year", "Schools Count", line_chart_dataset, PlotOrientation.VERTICAL, true, true, false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ File lineChart = new File("LineChart.jpeg"); ChartUtilities.saveChartAsJPEG(lineChart, lineChartObject, width, height); }
public void saveChart(JFreeChart chart, String fileLocation) { String fileName = fileLocation; try { ChartUtilities.saveChartAsJPEG(new File(fileName), chart, 800, 600); } catch (IOException e) { e.printStackTrace(); System.err.println("Error saving gant chart"); } }
protected void saveChart(BufferedImage img, String name) throws IOException { File target = new File("target/test-tmp/chart/"); FileUtils.forceMkdir(target); ByteArrayOutputStream imgOutput = new ByteArrayOutputStream(); ChartUtilities.writeBufferedImageAsPNG(imgOutput, img, true, 0); OutputStream out = new FileOutputStream(new File(target, name)); out.write(imgOutput.toByteArray()); out.close(); }
public void jpeg() throws IOException { this.response.setContentType("image/jpeg"); StandardChartTheme standardChartTheme = new StandardChartTheme(theme); setChartTheme(standardChartTheme); JFreeChart jFreeChart = createChart(); preRender(jFreeChart); ChartUtilities.writeChartAsJPEG(this.response.getOutputStream(), jFreeChart, width, height); }
public String generatePieChart( String hitOrdNum, HttpSession session, PrintWriter pw, String courseId, int studentId) { /* int groupId=0; if (groupName.equals("All")){ groupId=0; }else{ groupId = studStatisticBean.getGroupIdByName(groupName); }*/ String filename = null; try { // Retrieve list of WebHits StudentsConceptChartDataSet whDataSet = new StudentsConceptChartDataSet(studStatisticBean, courseId, studentId); ArrayList list = whDataSet.getDataBySection(hitOrdNum); // Throw a custom NoDataException if there is no data if (list.size() == 0) { System.out.println("No data has been found"); throw new NoDataException(); } // Create and populate a PieDataSet DefaultPieDataset data = new DefaultPieDataset(); Iterator iter = list.listIterator(); while (iter.hasNext()) { StudentsConceptHit wh = (StudentsConceptHit) iter.next(); data.setValue(wh.getSection(), wh.getHitDegree()); } // Create the chart object PiePlot plot = new PiePlot(data); plot.setInsets(new Insets(0, 5, 5, 5)); plot.setURLGenerator(new StandardPieURLGenerator("xy_chart.jsp", "section")); plot.setToolTipGenerator(new StandardPieItemLabelGenerator()); JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true); chart.setBackgroundPaint(java.awt.Color.white); // Write the chart image to the temporary directory ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); filename = ServletUtilities.saveChartAsPNG(chart, 600, 400, info, session); // Write the image map to the PrintWriter ChartUtilities.writeImageMap(pw, filename, info); pw.flush(); } catch (NoDataException e) { System.out.println(e.toString()); filename = "public_nodata_500x300.png"; } catch (Exception e) { System.out.println("Exception - " + e.toString()); e.printStackTrace(System.out); filename = "public_error_500x300.png"; } return filename; }
/** * Generates a byte array (a png image file) from a JFreeChart object * * @param chart A chart object from which the image is created * @param width Width of the created image * @param height Height of the created image * @return Byte array representing a png image file */ protected byte[] getChartImageByteArray(JFreeChart chart, int width, int height) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ChartUtilities.writeChartAsPNG(out, chart, width, height); return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null; }
/** * Plots the chart and sends it in the form of ByteArrayOutputStream to outside. * * @return Returns the byteArrayOutputStream. */ public synchronized ByteArrayOutputStream writePlot() { if (!changed) return byteArrayOutputStream; byteArrayOutputStream.reset(); try { ChartUtilities.writeChartAsPNG(byteArrayOutputStream, chart, width, height, false, 8); } catch (IOException e) { logger.warn(e.getMessage(), e); } return byteArrayOutputStream; }
public void writeXYsGraphic(final String fileName, final int numberOfBins) { JFreeChart chart = this.getTraveledXYsHistogram(numberOfBins); try { ChartUtilities.saveChartAsPNG(new File(fileName), chart, 1024, 768); } catch (IOException e) { log.error( "got an error while trying to write graphics to file." + " Error is not fatal, but output may be incomplete."); e.printStackTrace(); } }
/** Saves the chart image and HTML. */ public void saveImageAndHTML() { final CategoryDataset dataset = createDataset(); final JFreeChart chart = createChart(dataset); // **************************************************************************** // * JFREECHART DEVELOPER GUIDE * // * The JFreeChart Developer Guide, written by David Gilbert, is available * // * to purchase from Object Refinery Limited: * // * * // * http://www.object-refinery.com/jfreechart/guide.html * // * * // * Sales are used to provide funding for the JFreeChart project - please * // * support us so that we can continue developing free software. * // **************************************************************************** // save it to an image try { final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); final File file1 = new File("multipiechart100.png"); ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info); // write an HTML page incorporating the image with an image map final File file2 = new File("multipiechart100.html"); final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); final PrintWriter writer = new PrintWriter(out); writer.println("<HTML>"); writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>"); writer.println("<BODY>"); ChartUtilities.writeImageMap(writer, "chart", info, true); writer.println( "<IMG SRC=\"multipiechart100.png\" " + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">"); writer.println("</BODY>"); writer.println("</HTML>"); writer.close(); } catch (IOException e) { System.out.println(e.toString()); } }
public JFreeChart createChart(int size) { CategoryDataset paramCategoryDataset = createDataset(size); // 创建主题样式 StandardChartTheme standardChartTheme = new StandardChartTheme("CN"); // 设置标题字体 standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20)); // 设置图例的字体 standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 12)); // 设置轴向的字体 standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 12)); // 应用主题样式 ChartFactory.setChartTheme(standardChartTheme); JFreeChart localJFreeChart = ChartFactory.createLineChart( title, "期号", yTitle, paramCategoryDataset, PlotOrientation.VERTICAL, true, true, false); CategoryPlot localCategoryPlot = (CategoryPlot) localJFreeChart.getPlot(); // SymbolAxis localSymbolAxis = new SymbolAxis("个数", new String[] { // "0", "1", "2", "3", "4", "5", "6" }); // localCategoryPlot.setRangeAxis(localSymbolAxis); ChartUtilities.applyCurrentTheme(localJFreeChart); LineAndShapeRenderer xyitem = (LineAndShapeRenderer) localCategoryPlot.getRenderer(); CategoryPlot plot = (CategoryPlot) localJFreeChart.getPlot(); // 设置网格背景颜色 plot.setBackgroundPaint(Color.white); // 设置网格竖线颜色 plot.setDomainGridlinePaint(Color.black); // 设置网格横线颜色 plot.setRangeGridlinePaint(Color.black); // 设置曲线图与xy轴的距离 plot.setAxisOffset(new RectangleInsets(0D, 0D, 0D, 0D)); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); rangeAxis.setAutoRangeIncludesZero(true); if ("和值".equals(type)) { rangeAxis.setLowerBound(70); rangeAxis.setTickUnit(new NumberTickUnit(10)); } else { rangeAxis.setLowerBound(0); rangeAxis.setTickUnit(new NumberTickUnit(1)); } // rangeAxis.setUpperMargin(0.20); // 设置曲线显示各数据点的值 xyitem.setBaseItemLabelsVisible(true); xyitem.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); xyitem.setSeriesStroke(0, new BasicStroke(1.5F)); xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 14)); xyitem.setSeriesShapesVisible(0, true); plot.setRenderer(xyitem); return localJFreeChart; }
@SuppressWarnings("unchecked") public void exportTo(OutputStream os, int width, int height) { Query query = buildQuery(); List<GroupedDataTuple<T>> results = query.list(); JFreeChart finalChart = chart.build(convertTo(results)); try { ChartUtilities.writeChartAsJPEG(os, finalChart, width, height); } catch (Exception e) { throw new RuntimeException(e); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("image/png"); OutputStream outputStream = response.getOutputStream(); CategoryDataset dataset = createDataset(); JFreeChart chart = getChart(dataset); int width = 400; int height = 250; ChartUtilities.writeChartAsPNG(outputStream, chart, width, height); }