/** {@inheritDoc} */ @Override protected JFreeChart createChart() { PieDataset dataSet = createDataset(); JFreeChart chart = ChartFactory.createPieChart(dataDescription, dataSet, drawLegend, true, false); PiePlot plot = (PiePlot) chart.getPlot(); setColors(plot, dataSet); plot.setLabelGenerator(new StandardPieSectionLabelGenerator(labelFormat)); stylePiePlot(plot); return chart; }
/** * 设置饼图使用的字体 * * @param chart */ public void setPiePoltFont(JFreeChart chart) { // 图表(饼图) PiePlot piePlot = (PiePlot) chart.getPlot(); piePlot.setLabelFont(new Font("宋体", Font.PLAIN, 14)); piePlot.setLabelGenerator(new StandardPieSectionLabelGenerator("{1}")); // 标题 TextTitle textTitle = chart.getTitle(); textTitle.setFont(new Font("宋体", Font.BOLD, 20)); // 图例 LegendTitle legendTitle = chart.getLegend(); legendTitle.setItemFont(new Font("宋体", Font.PLAIN, 12)); }
private PdfPCell createKPGSPieChartCell(KeyValue[] values, String title) throws IOException, BadElementException { DefaultPieDataset dataset = new DefaultPieDataset(); for (int n = 0; n < values.length; n++) { dataset.setValue(values[n].getKey(), new Double(values[n].getValue()).doubleValue()); } // create chart final JFreeChart chart = ChartFactory.createPieChart( title, // chart title dataset, // data true, // legend false, // tooltips false // urls ); // customize chart PiePlot plot = (PiePlot) chart.getPlot(); plot.setBackgroundPaint(java.awt.Color.WHITE); if (values.length > 0) { if (values[0].getKey().equalsIgnoreCase("?") && values.length > 1) { plot.setExplodePercent(values[1].getKey(), 0.2); } else { plot.setExplodePercent(values[0].getKey(), 0.2); } } plot.setLegendLabelGenerator(new KPGSLegendGenerator()); plot.setLabelGenerator(new KPGSLabelGenerator(values)); plot.setOutlineVisible(false); chart.setAntiAlias(true); LegendTitle legendTitle = (LegendTitle) chart.getSubtitle(0); legendTitle.setFrame(BlockBorder.NONE); legendTitle.setBackgroundPaint(null); ByteArrayOutputStream os = new ByteArrayOutputStream(); ChartUtilities.writeChartAsPNG( os, chart, MedwanQuery.getInstance().getConfigInt("stats.piechartwidth", 640), MedwanQuery.getInstance().getConfigInt("stats.piechartheight", 480)); cell = new PdfPCell(); cell.setColspan(50); cell.setImage(Image.getInstance(os.toByteArray())); cell.setBorder(PdfPCell.NO_BORDER); cell.setPaddingLeft(5); cell.setPaddingRight(5); return cell; }
/** * Creates a sample chart with the given dataset. * * @param dataset the dataset. * @return A sample chart. */ private JFreeChart createChart(final CategoryDataset dataset) { final JFreeChart chart = ChartFactory.createMultiplePieChart( "Multiple Pie Chart", // chart title dataset, // dataset TableOrder.BY_ROW, true, // include legend true, true); final MultiplePiePlot plot = (MultiplePiePlot) chart.getPlot(); final JFreeChart subchart = plot.getPieChart(); final PiePlot p = (PiePlot) subchart.getPlot(); p.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}")); p.setLabelFont(new Font("SansSerif", Font.PLAIN, 8)); p.setInteriorGap(0.30); return chart; }
/** * 円グラフ用のラベル設定メソッド * * @param doc XML文書(JFreeChart用XMLドキュメント) */ public void setPieLabel(Document doc) { Element root = doc.getDocumentElement(); Element chartInfo = (Element) root.getElementsByTagName("ChartInfo").item(0); String hasPieLabel = chartInfo.getElementsByTagName("hasPieLabel").item(0).getFirstChild().getNodeValue(); // 円グラフ用のラベルを「非表示」に設定 String falseString = Boolean.FALSE.toString(); if ("0".equals(hasPieLabel)) { PiePlot piePlot = this.getPiePlot(); piePlot.setLabelGenerator(null); } else { // 円グラフのデフォルトラベル設定は「表示」であるため、何もしなくてよい } }
private BufferedImage generarGraficoTorta( String titulo, double[] valores, String[] funciones, int anchoImagen, int altoImagen) { if (valores.length != funciones.length) { return null; } DefaultPieDataset pieDataset = new DefaultPieDataset(); for (int i = 0; i < valores.length; i++) { pieDataset.setValue(funciones[i], valores[i]); } JFreeChart chart = ChartFactory.createPieChart(titulo, pieDataset, true, true, false); chart.setBackgroundPaint(null); chart.getTitle().setPaint(LookAndFeelEntropy.COLOR_FUENTE_TITULO_PANEL); chart.getTitle().setFont(LookAndFeelEntropy.FUENTE_TITULO_GRANDE); chart.setBorderVisible(false); chart.getLegend().setItemFont(LookAndFeelEntropy.FUENTE_REGULAR); chart.getLegend().setBackgroundPaint(LookAndFeelEntropy.COLOR_TABLA_PRIMARIO); PiePlot plot = (PiePlot) chart.getPlot(); plot.setBackgroundPaint(null); plot.setBackgroundImageAlpha(0.0f); plot.setSimpleLabels(true); plot.setOutlineVisible(false); for (int i = 0; i < valores.length; i++) { plot.setSectionPaint( funciones[i], generarColorAleatorio(Color.ORANGE)); // LookAndFeelEntropy.COLOR_FUENTE_TITULO_PANEL)); plot.setExplodePercent(funciones[i], 0.10); } PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator( "{0}: {1} ({2})", new DecimalFormat("0"), new DecimalFormat("0%")); plot.setLabelGenerator(gen); this.lastChart = chart; // Generamos una imagen return chart.createBufferedImage(anchoImagen, altoImagen); }
private JFreeChart getPieChart() { // Load the data, if necessary loadData(); // Create a chart and return it final JFreeChart chart = ChartFactory.createPieChart( getTitle(), getPieDataset(), useLegend(), useTooltips(), useURLs()); // Customize the labels and legend final PiePlot pieplot = (PiePlot) chart.getPlot(); pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2})")); // pieplot.setSimpleLabels(true); pieplot.setNoDataMessage("No data available"); if (useLegend()) { pieplot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({1})")); chart.getLegend().setPosition(RectangleEdge.RIGHT); // pieplot.setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("{0}: {2}%")); } return chart; }
/** * Creates a chart containing multiple pie charts, from a TableDataset. * * @param title the chart title. * @param data the dataset for the chart. * @param extractType <code>PER_ROW</code> or <code>PER_COLUMN</code> (defined in {@link * PiePlot}). * @param legend a flag specifying whether or not a legend is required. * @param tooltips configure chart to generate tool tips? * @param urls configure chart to generate URLs? * @return a pie chart. */ public static JFreeChart createPieChart( String title, java.awt.Font titleFont, CategoryDataset data, TableOrder order, boolean legend, boolean tooltips, boolean urls, PieURLGenerator urlGenerator) { MultiplePiePlot plot = new MultiplePiePlot(data); plot.setDataExtractOrder(order); PiePlot pp = (PiePlot) plot.getPieChart().getPlot(); // pp.setInsets(new Insets(0, 5, 5, 5)); pp.setBackgroundPaint(null); // no outline around each piechart pp.setOutlineStroke(null); // plot.setOutlineStroke(null); PieToolTipGenerator tooltipGenerator = null; if (tooltips) { tooltipGenerator = new StandardPieToolTipGenerator(); } // PieURLGenerator urlGenerator = null; if (!urls) { urlGenerator = null; } pp.setToolTipGenerator(tooltipGenerator); pp.setLabelGenerator(null); pp.setURLGenerator(urlGenerator); JFreeChart chart = new JFreeChart(title, titleFont, plot, legend); return chart; }
/** * Default constructor. * * @param title the frame title. */ public XMLPieChartDemo(final String title) { super(title); // create a dataset... PieDataset dataset = null; final URL url = getClass().getResource("/org/jfree/chart/demo/piedata.xml"); try { final InputStream in = url.openStream(); dataset = DatasetReader.readPieDatasetFromXML(in); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } // create the chart... final JFreeChart chart = ChartFactory.createPieChart( "Pie Chart Demo 1", // chart title dataset, // data true, // include legend true, false); // set the background color for the chart... chart.setBackgroundPaint(Color.yellow); final PiePlot plot = (PiePlot) chart.getPlot(); plot.setLabelGenerator( new StandardPieItemLabelGenerator( "{0} = {2}", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance())); plot.setNoDataMessage("No data available"); // add the chart to a panel... final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); setContentPane(chartPanel); }
public static JFreeChart createPieChart(String chartName, DBSeerDataSet dataset) { StatisticalPackageRunner runner = DBSeerGUI.runner; runner.eval( "[title legends Xdata Ydata Xlabel Ylabel timestamp] = plotter.plot" + chartName + ";"); String title = runner.getVariableString("title"); Object[] legends = (Object[]) runner.getVariableCell("legends"); Object[] xCellArray = (Object[]) runner.getVariableCell("Xdata"); Object[] yCellArray = (Object[]) runner.getVariableCell("Ydata"); String xLabel = runner.getVariableString("Xlabel"); String yLabel = runner.getVariableString("Ylabel"); timestamp = runner.getVariableDouble("timestamp"); DefaultPieDataset pieDataSet = new DefaultPieDataset(); int numLegends = legends.length; int numXCellArray = xCellArray.length; int numYCellArray = yCellArray.length; int dataCount = 0; if (numXCellArray != numYCellArray) { JOptionPane.showMessageDialog( null, "The number of X dataset and Y dataset does not match.", "The number of X dataset and Y dataset does not match.", JOptionPane.ERROR_MESSAGE); return null; } final java.util.List<String> transactionTypeNames = dataset.getTransactionTypeNames(); for (int i = 0; i < numYCellArray; ++i) { double[] xArray = (double[]) xCellArray[i]; runner.eval("yArraySize = size(Ydata{" + (i + 1) + "});"); runner.eval("yArray = Ydata{" + (i + 1) + "};"); double[] yArraySize = runner.getVariableDouble("yArraySize"); double[] yArray = runner.getVariableDouble("yArray"); int xLength = xArray.length; int row = (int) yArraySize[0]; int col = (int) yArraySize[1]; for (int c = 0; c < col; ++c) { if (c < transactionTypeNames.size()) { String name = transactionTypeNames.get(c); if (!name.isEmpty()) { // pieDataSet.setValue(name, new Double(yArray.getRealValue(0, c))); pieDataSet.setValue(name, yArray[c]); } else { // pieDataSet.setValue("Transaction Type " + (c+1), yArray.getRealValue(0, c)); pieDataSet.setValue("Transaction Type " + (c + 1), yArray[c]); } } } } JFreeChart chart = ChartFactory.createPieChart(title, pieDataSet, true, true, false); PiePlot plot = (PiePlot) chart.getPlot(); plot.setLabelGenerator( new StandardPieSectionLabelGenerator( "{0}: {1} ({2})", new DecimalFormat("0"), new DecimalFormat("0%"))); plot.setLegendLabelGenerator( new PieSectionLabelGenerator() { @Override public String generateSectionLabel(PieDataset pieDataset, Comparable comparable) { return (String) comparable; } @Override public AttributedString generateAttributedSectionLabel( PieDataset pieDataset, Comparable comparable) { return null; } }); return chart; }
/* (non-Javadoc) * @see com.lily.dap.service.report2.impl.chart.ChartStrategy#outputChart(java.lang.String, int, int, java.util.Map, java.util.List, java.io.OutputStream) */ public void outputChart( String type, int height, int width, Map<String, String> paramMap, Map<String, Object> variableMap, List<Map<String, Object>> dataList, OutputStream os) throws IOException { String nameField = ChartUtils.evaluateParam(paramMap.get("namefield"), variableMap); String valueField = ChartUtils.evaluateParam(paramMap.get("valuefield"), variableMap); DefaultPieDataset dataset = createDataset(dataList, nameField, valueField); String title = ChartUtils.evaluateParam(paramMap.get("title"), variableMap); boolean legend = paramMap.get("legend") == null ? true : "true" .equals( ChartUtils.evaluateParam(paramMap.get("legend"), variableMap).toLowerCase()); JFreeChart chart; if (ChartConstants.TYPE_PIE3D.equals(type)) chart = ChartFactory.createPieChart3D( title, // 图表标题 dataset, // 数据集 legend, // 是否显示图例 false, // 是否生成工具 false // 是否生成URL链接 ); else chart = ChartFactory.createPieChart( title, // 图表标题 dataset, // 数据集 legend, // 是否显示图例 false, // 是否生成工具 false // 是否生成URL链接 ); // 设置标题字体 if (chart.getTitle() != null) chart.getTitle().setFont(titleFont); // 设置图例字体 if (chart.getLegend() != null) chart.getLegend().setItemFont(legendFont); PiePlot pie = (PiePlot) chart.getPlot(); // if (pie instanceof PiePlot3D) { // PiePlot3D pie3d = (PiePlot3D)pie; // } // 设置前景透明度 if (paramMap.get("foregroundAlpha") != null) { float f = Float.parseFloat(ChartUtils.evaluateParam(paramMap.get("foregroundAlpha"), variableMap)); pie.setForegroundAlpha(f); } // 设置标签的最大宽度 if (paramMap.get("maximumlabelwidth") != null) { float f = Float.parseFloat( ChartUtils.evaluateParam(paramMap.get("maximumlabelwidth"), variableMap)); pie.setMaximumLabelWidth(f); } // 设置标饼上标签的标签字体 pie.setLabelFont(labelFont); String labelFormat = paramMap.get("labelformat"); if (labelFormat != null) { /* * 因为labelformat参数可能包含{0}、{1}、{2}这样的字符串,所以要通过检查'{'后面跟的字符是不是数字,来判断labelformat参数是不是表达式 */ int index = labelFormat.indexOf('{'); if (index >= 0) { char ch = labelFormat.charAt(index + 1); if (!CharUtils.isAsciiNumeric(ch)) labelFormat = ChartUtils.evaluateParam(labelFormat, variableMap); } // 设置饼上标签的显示格式,其中,0:数据名称,1:数据值,2:数据占整个百分比 StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator(labelFormat); pie.setLabelGenerator(generator); } String legendformat = paramMap.get("legendformat"); if (legendformat != null) { /* * 因为legendformat参数可能包含{0}、{1}、{2}这样的字符串,所以要通过检查'{'后面跟的字符是不是数字,来判断legendformat参数是不是表达式 */ int index = legendformat.indexOf('{'); if (index >= 0) { char ch = legendformat.charAt(index + 1); if (!CharUtils.isAsciiNumeric(ch)) legendformat = ChartUtils.evaluateParam(legendformat, variableMap); } // 设置饼上标签的显示格式,其中,0:数据名称,1:数据值,2:数据占整个百分比 StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator(legendformat); pie.setLegendLabelGenerator(generator); } if (paramMap.get("color") != null) { int index = 0; String[] colGroups = ChartUtils.evaluateParam(paramMap.get("color"), variableMap).split(","); for (String colVal : colGroups) { Color color = ChartUtils.createColor(colVal.trim()); pie.setSectionPaint(index++, color); } } // 设置饼图是圆形还是椭圆形 if (paramMap.get("circular") != null) { boolean isCircular = "true" .equals( ChartUtils.evaluateParam(paramMap.get("circular"), variableMap).toLowerCase()); pie.setCircular(isCircular); } ChartUtilities.writeChartAsJPEG(os, 1, chart, width, height, null); }