JFreeChart 1.0中PieChart, BarChart詳細設定

來源:互聯網
上載者:User

版本JFreeChart 1.0.12

代碼如下:

 

// $Id: ChartServiceImpl.java, v1.0 2010-1-15 下午06:56:24 wuyao Exp $<br />package com.owen.chart.mine;<br />import java.awt.Color;<br />import java.awt.Font;<br />import java.awt.GradientPaint;<br />import java.awt.Paint;<br />import java.io.IOException;<br />import java.io.OutputStream;<br />import java.text.DecimalFormat;<br />import java.text.NumberFormat;<br />import org.jfree.chart.ChartFactory;<br />import org.jfree.chart.ChartUtilities;<br />import org.jfree.chart.JFreeChart;<br />import org.jfree.chart.axis.CategoryAxis;<br />import org.jfree.chart.axis.NumberAxis;<br />import org.jfree.chart.axis.ValueAxis;<br />import org.jfree.chart.block.BlockContainer;<br />import org.jfree.chart.block.BorderArrangement;<br />import org.jfree.chart.block.LabelBlock;<br />import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;<br />import org.jfree.chart.labels.StandardPieSectionLabelGenerator;<br />import org.jfree.chart.plot.CategoryPlot;<br />import org.jfree.chart.plot.PiePlot;<br />import org.jfree.chart.plot.PiePlot3D;<br />import org.jfree.chart.plot.PlotOrientation;<br />import org.jfree.chart.renderer.category.BarRenderer;<br />import org.jfree.chart.title.LegendTitle;<br />import org.jfree.chart.title.TextTitle;<br />import org.jfree.data.category.CategoryDataset;<br />import org.jfree.data.general.PieDataset;<br />import org.jfree.ui.RectangleEdge;<br />import org.jfree.ui.VerticalAlignment;<br />import org.jfree.util.Rotation;<br />/**<br /> *<br /> * @author wuyao;<br /> * @version 1.0, $Revision: 1.0 $, $Date: 2010-1-15 下午06:56:24 $<br /> */<br />public class ChartServiceImpl {<br />public JFreeChart createBarChart(CategoryDataset dataset, String title,<br />String catAxisLabel, String valAxisLabel) {<br />// if no dataset, don't generate chart<br />if(dataset == null) return null; </p><p>JFreeChart chart = ChartFactory.createBarChart(title, // char title<br />catAxisLabel, // categoryAxisLabel<br />valAxisLabel, // valueAxisLabel<br />dataset, // the dataset for the chart<br />PlotOrientation.VERTICAL, //<br />false, // legend if is needed<br />false, // tooltips if is needed<br />false // urls<br />);<br />//<br />customizeBarChart(chart);<br />//</p><p>return chart;<br />}<br />public JFreeChart createPieChart(PieDataset dataset, String title) {<br />// if no dataset, don't generate chart<br />if(dataset == null) return null; </p><p>JFreeChart chart = ChartFactory.createPieChart(title, // chart title<br />dataset, // data<br />true, // include legend<br />true, // include tooltip<br />false);<br />// customize the chart<br />customizePieChart(chart);<br />// customize for pie<br />PiePlot plot = (PiePlot) chart.getPlot();<br />plot.setSectionOutlinesVisible(true);<br />plot.setNoDataMessage("No data available");<br />return chart;<br />}</p><p>public JFreeChart create3DBarChart(CategoryDataset dataset, String title,<br />String catAxisLabel, String valAxisLabel) {<br />// if no dataset, don't generate chart<br />if(dataset == null) return null; </p><p>JFreeChart chart = ChartFactory.createBarChart3D(title, // 圖表標題<br />catAxisLabel, // 目錄軸的顯示標籤<br />valAxisLabel, // 數值軸的顯示標籤<br />dataset, // 資料集<br />PlotOrientation.VERTICAL, // 圖表方向:水平、垂直<br />false, // 是否顯示圖例(對於簡單的柱狀圖必須是false)<br />false, // 是否產生工具<br />false // 是否產生URL連結<br />);<br />// basic customization<br />customizeBarChart(chart);</p><p>// additional customization</p><p>return chart;<br />}<br />public JFreeChart create3DPieChart(PieDataset dataset, String title) {<br />// if no dataset, don't generate chart<br />if(dataset == null) return null; </p><p>JFreeChart chart = ChartFactory.createPieChart3D(title, // chart title<br />dataset, // data<br />true, // include legend<br />true, // incluse tooltip<br />false);<br />// customize the font of the chart<br />customizePieChart(chart);<br />// additional customize for 3D effect<br />PiePlot3D plot = (PiePlot3D) chart.getPlot();<br />plot.setStartAngle(290);<br />plot.setDirection(Rotation.CLOCKWISE);<br />plot.setForegroundAlpha(0.5f);<br />return chart;<br />}<br />/**<br /> * Customize the pie chart, such as adjust font, legend.<br /> * @param chart<br /> */<br />private void customizePieChart(JFreeChart chart) {<br />// 定義整張圖片的背景顏色: GradientPaint漸層色<br />Paint bgPaint = new GradientPaint(50, 0, new Color(0xD1DEEF), 50, 700, new Color(0xFFFFFF));<br />chart.setBackgroundPaint(bgPaint); // set chart bg<br />chart.setBorderPaint(Color.GREEN);<br />chart.setBorderVisible(false); // set chart border, true in debug mode</p><p>PiePlot plot = (PiePlot) chart.getPlot(); // 擷取餅圖圖表區域<br />plot.setBackgroundPaint(bgPaint); // 設定圖表區域背景顏色<br />plot.setBackgroundAlpha(0.0f); // 設定此地區背景色透明度<br />plot.setOutlineVisible(false); // 設定是否顯示邊框,true in debug mode</p><p>plot.setNoDataMessage("無對應的資料,請重新查詢。");<br />// 設定中文字型<br />Font titleFont = new Font("宋體", Font.PLAIN, 14); // 圖表標題字型<br />Font contentFont = new Font("宋體", Font.PLAIN, 12); // 圖表內容字型<br />Font legendFont = new Font("宋體", Font.PLAIN, 12); // 圖例字型<br />// 設定圖表標題屬性<br />TextTitle title = chart.getTitle();<br />title.setFont(titleFont);<br />title.setMargin(10, 0, 0, 0);<br />// 設定圖表內容字型<br />plot.setLabelFont(contentFont);<br />/*<br /> * 是標籤格式(預設是“{0} = {1}”這樣是顯示資料),<br /> * {0}是類別名,{1}是實際資料,後面的{2}是百分比。<br /> */<br />String unitSytle = "{0}: {1}({2})"; // {2}</p><p>// 設定圖表圖例字型和位置<br />LegendTitle legend = chart.getLegend();<br />if (legend != null) {<br />legend.setItemFont(legendFont);<br />legend.setPosition(RectangleEdge.RIGHT);<br />legend.setVerticalAlignment(VerticalAlignment.TOP);<br />legend.setBackgroundPaint(bgPaint);<br />legend.setBorder(0.0, 0, 0.0, 0); // (0.5, 0, 0.5, 0) in test mode</p><p>// 為圖例添加描述資訊<br />LabelBlock labelblock = new LabelBlock("圖例:", legendFont);<br />BlockContainer blockcontainer = new BlockContainer(<br />new BorderArrangement());<br />blockcontainer.add(labelblock, RectangleEdge.TOP);<br />// 添加圖例本身<br />BlockContainer itemContainer = legend.getItemContainer();<br />blockcontainer.add(itemContainer);<br />legend.setWrapper(blockcontainer);<br />// </p><p>}</p><p> //引出標籤顯示樣式,在圖表上顯示比例<br /> plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({2})"/*unitSytle*/,<br /> NumberFormat.getNumberInstance(),<br /> new DecimalFormat("0.00%"))); </p><p> //圖例顯示樣式<br /> plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(unitSytle,<br /> NumberFormat.getNumberInstance(),<br /> new DecimalFormat("0.00%")));<br />}<br />/**<br /> * Customize bar chart for font, background<br /> * @param chart<br /> */<br />private void customizeBarChart(JFreeChart chart) {<br />// 定義整張圖片的背景顏色: GradientPaint漸層色<br />Paint bgPaint = new GradientPaint(50, 0, new Color(0xD1DEEF), 50, 700, new Color(0xFFFFFF));<br />chart.setBackgroundPaint(bgPaint); // set chart bg<br />chart.setBorderPaint(Color.GREEN);<br />chart.setBorderVisible(false); // set chart border, true in debug mode</p><p>// 設定圖表區域<br />CategoryPlot cplot = chart.getCategoryPlot(); // 擷取餅圖圖表區域<br />cplot.setBackgroundAlpha(0.0f); // 設定此地區背景色透明度<br />cplot.setOutlineVisible(false); // 設定是否顯示邊框,true in debug mode</p><p>// solve Chinese character messy code of chart title.<br />Font titleFont = new Font("宋體", Font.PLAIN, 14);<br />Font xyTitleFont = new Font("宋體", Font.PLAIN, 12);<br />Font xyCoordFont = new Font("宋體", Font.PLAIN, 12);<br />Font legendFont = new Font("宋體", Font.PLAIN, 12);<br />Font contentFont = new Font("宋體", Font.PLAIN, 12);</p><p>// 設定圖表標題屬性<br />TextTitle title = chart.getTitle();<br />title.setFont(titleFont);<br />title.setMargin(15, 0, 10, 0);<br />//<br />CategoryAxis axis = cplot.getDomainAxis();<br />// Set font on X-axis title 設定X座標軸上標題字型<br />axis.setLabelFont(xyTitleFont);<br />// Set font on X-axis coordinate, 設定X座標軸上刻度字型<br />axis.setTickLabelFont(xyCoordFont);<br />//<br />ValueAxis vAxis = cplot.getRangeAxis();<br />// set the Y-axis title font<br />vAxis.setLabelFont(xyTitleFont);<br />// set the Y-axis coordinate title font<br />vAxis.setTickLabelFont(xyCoordFont);</p><p>vAxis.setUpperMargin(0.1); // 設定最高柱子離頂端的間距<br />// 設定Y軸座標間距<br />NumberAxis numAxis = (NumberAxis)cplot.getRangeAxis();<br />numAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());</p><p>// set legend font 如果有圖例,設定其字型和位置<br />LegendTitle legend = chart.getLegend();<br />if (legend != null) {<br />legend.setItemFont(legendFont);<br />legend.setPosition(RectangleEdge.RIGHT);<br />}</p><p>// 設定表徵圖屬性<br />// change the color of the chart<br />cplot.setBackgroundPaint(new Color(212, 225, 241));<br />cplot.setDomainGridlinePaint(Color.GRAY); // 設定表中豎輔助線的顏色<br />cplot.setDomainGridlinesVisible(true); // 設定豎輔助線是否顯示<br />// 設定橫輔助線屬性<br />cplot.setRangeGridlinePaint(Color.BLUE);<br />cplot.setRangeGridlinesVisible(true);<br />cplot.setForegroundAlpha(1.0f); // 設定前景透明度(1.0f不透明)<br />BarRenderer crender = (BarRenderer) cplot.getRenderer(); //new BarRenderer();<br />// 設定柱子的形狀屬性<br />crender.setSeriesPaint(0, Color.BLUE); // 柱子顏色: 綠色new Color(0x3882EF),new Color(0x7170F0)<br />crender.setMaximumBarWidth(0.15); // 設定柱子寬度<br />// 設定顯示柱子顯示資料<br />crender.setSeriesItemLabelGenerator(0, new StandardCategoryItemLabelGenerator());<br />crender.setSeriesItemLabelFont(0, contentFont);<br />crender.setSeriesItemLabelsVisible(0, true);</p><p>}<br />/**<br /> * 產生柱子的資料顯示<br /> * @author wuyao<br /> *<br /> */<br />static class LabelGenerator extends StandardCategoryItemLabelGenerator {<br />/**<br /> *<br /> */<br />private static final long serialVersionUID = 7335548557126787550L;<br />public String generateItemLabel(CategoryDataset categorydataset, int i,<br />int j) {<br />return categorydataset.getRowKey(i).toString();<br />}<br />LabelGenerator() {<br />}<br />}<br />/**<br /> * Just for testing<br /> * @param chart<br /> * @param out<br /> */<br />public void writeChart(JFreeChart chart, OutputStream out) {<br />try {<br />ChartUtilities.writeChartAsJPEG(out, 1.0f, chart, 800, 600, null);<br />} catch (IOException e) {<br />// just throw it, or throw to high level Exception<br />throw new RuntimeException(e);<br />} finally {<br />try {<br />out.close();<br />} catch (IOException e) {<br />// just throw it, or throw to high level Exception<br />throw new RuntimeException(e);<br />}<br />}<br />}<br />}<br />

 

一個簡單的測試:

// $Id: ChartServiceTest.java, v1.0 2010-1-15 下午07:04:37 wuyao Exp $<br />package com.owen.chart.mine;<br />import java.io.FileNotFoundException;<br />import java.io.FileOutputStream;<br />import java.io.IOException;<br />import org.jfree.chart.JFreeChart;<br />import org.jfree.data.category.CategoryDataset;<br />import org.jfree.data.category.DefaultCategoryDataset;<br />import org.jfree.data.general.DefaultPieDataset;<br />import org.jfree.data.general.PieDataset;<br />/**<br /> *<br /> * @author wuyao;<br /> * @version 1.0, $Revision: 1.0 $, $Date: 2010-1-15 下午07:04:37 $<br /> */<br />public class ChartServiceTest {<br />public static void main(String[] args) throws IOException {<br />ChartServiceImpl chartService = new ChartServiceImpl();<br />ChartServiceTest test = new ChartServiceTest();<br />// test pie chart<br />PieDataset pieDataset = test.createPieDataset();<br />JFreeChart pieChart = chartService.createPieChart(pieDataset,<br />"pie chart測試");<br />FileOutputStream pieOut = new FileOutputStream(<br />"C://Users//wuyao//Desktop//pieOut.jpg");<br />chartService.writeChart(pieChart, pieOut);<br />// test bar chart<br />CategoryDataset barDataset = test.createBarDataset();<br />JFreeChart barChart = chartService.createBarChart(barDataset,<br />"bar chart測試", "水果", "產量");<br />FileOutputStream barOut = new FileOutputStream(<br />"C://Users//wuyao//Desktop//barOut.jpg");<br />chartService.writeChart(barChart, barOut);<br />}<br />private PieDataset createPieDataset() {<br />DefaultPieDataset result = new DefaultPieDataset();<br />result.setValue("Linux系統", 35);<br />result.setValue("Mac系統", 20);<br />result.setValue("Windows系統", 68);<br />return result;<br />}<br />private CategoryDataset createBarDataset() {<br />DefaultCategoryDataset dataset = new DefaultCategoryDataset();<br />dataset.setValue(23.4f, "重慶", "橘子");<br />dataset.setValue(53.2f, "重慶", "蘋果");<br />dataset.setValue(34.9f, "重慶", "葡萄");<br />dataset.setValue(65.6f, "重慶", "香蕉");<br />dataset.setValue(29.1f, "重慶", "核桃");<br />return dataset;<br />}<br />}<br />

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.