jfreechart繪圖工具類

基於jfreechart1.x+++java

package com.wdh.util;
 
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.RenderingHints;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
 
import org.apache.commons.logging.Log;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYBoxAnnotation;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.data.xy.DefaultXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.TextAnchor;
 
public class ChartUtil {
 
public static String createPieChart3D(String title, PieDataset dataset,
String path) {
JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true,
true, Locale.CHINA);
 
// 使下面的說明標籤字體清晰,相似於去鋸齒的效果
chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
chart.setTextAntiAlias(false);
// 圖片背景色
chart.setBackgroundPaint(Color.white);
 
// 設置圖標題的字體從新設置title(否組有些版本Title會出現亂碼)
chart.getTitle().setFont((new Font("隸書", Font.CENTER_BASELINE, 20)));
 
// 設置圖例(Legend)上的文字(//底部的字體)
chart.getLegend().setItemFont(new Font("隸書", Font.CENTER_BASELINE, 15));
 
PiePlot3D plot = (PiePlot3D) chart.getPlot();
// 圖片中顯示百分比:默認方式
 
// 指定餅圖輪廓線的顏色
plot.setBaseSectionOutlinePaint(Color.BLACK);
plot.setBaseSectionPaint(Color.BLACK);
 
// 設置無數據時的信息
plot.setNoDataMessage("無對應的數據,請從新查詢。");
 
// 設置無數據時的信息顯示顏色
plot.setNoDataMessagePaint(Color.red);
 
// 圖片中顯示百分比:自定義方式,{0} 表示選項, {1} 表示數值, {2} 表示所佔比例 ,小數點後兩位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
"{0}={1}({2})", NumberFormat.getNumberInstance(),
new DecimalFormat("0.00%")));
// 圖例顯示百分比:自定義方式, {0} 表示選項, {1} 表示數值, {2} 表示所佔比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(
"{0}({2})"));
 
plot.setLabelFont(new Font("隸書", Font.TRUETYPE_FONT, 12));
 
// 指定圖片的透明度(0.0-1.0)
plot.setForegroundAlpha(0.65f);
// 指定顯示的餅圖上圓形(false)還橢圓形(true)
plot.setCircular(false, true);
 
// 設置第一個 餅塊section 的開始位置,默認是12點鐘方向
plot.setStartAngle(90);
 
// 設置分餅顏色(不設置它會本身設置)
// plot.setSectionPaint(pieKeys[0], new Color(244, 194, 144));
// plot.setSectionPaint(pieKeys[1], new Color(144, 233, 144));
 
// 把餅圖生成圖片
String chartName = "";
FileOutputStream fos_jpg = null;
try {
// 文件夾不存在則建立
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
chartName = path + File.separator + new Date().getTime() + ".png";
fos_jpg = new FileOutputStream(chartName);
// 高寬的設置影響橢圓餅圖的形狀
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);
 
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos_jpg.close();// http://1wangxiaobo@163.com
} catch (Exception e) {
e.printStackTrace();
}
return chartName;
}
}
 
public static String createLineChart(String title, String domainAxisName,
String rangeAxisName, DefaultCategoryDataset ds, String path) {
JFreeChart chart = ChartFactory.createLineChart3D(title, domainAxisName,
rangeAxisName, ds, PlotOrientation.VERTICAL, // 繪製方向
true, // 顯示圖例
true, // 採用標準生成器
false // 是否生成超連接
);
chart.getTitle().setFont((new Font("隸書", Font.CENTER_BASELINE, 20))); // 設置標題字體
chart.getLegend().setItemFont(new Font("隸書", Font.CENTER_BASELINE, 15));// 設置圖例類別字體
// 獲取繪圖區對象
CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.LIGHT_GRAY); // 設置繪圖區背景色
plot.setRangeGridlinePaint(Color.WHITE); // 設置水平方向背景線顏色
plot.setRangeGridlinesVisible(true);// 設置是否顯示水平方向背景線,默認值爲true
plot.setDomainGridlinePaint(Color.WHITE); // 設置垂直方向背景線顏色
plot.setDomainGridlinesVisible(true); // 設置是否顯示垂直方向背景線,默認值爲false
 
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(new Font("隸書", Font.CENTER_BASELINE, 15)); // 設置橫軸字體
// domainAxis.setTickLabelFont(font);// 設置座標軸標尺值字體
domainAxis.setLowerMargin(0.01);// 左邊距 邊框距離
domainAxis.setUpperMargin(0.06);// 右邊距 邊框距離,防止最後邊的一個數據靠近了座標軸。
domainAxis.setMaximumCategoryLabelLines(2);
 
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(new Font("隸書", Font.CENTER_BASELINE, 15));
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());// Y軸顯示整數
rangeAxis.setAutoRangeMinimumSize(1); // 最小跨度
rangeAxis.setUpperMargin(0.18);// 上邊距,防止最大的一個數據靠近了座標軸。
rangeAxis.setLowerBound(0); // 最小值顯示0
rangeAxis.setAutoRange(false); // 不自動分配Y軸數據
rangeAxis.setTickMarkStroke(new BasicStroke(1.6f)); // 設置座標標記大小
rangeAxis.setTickMarkPaint(Color.BLACK); // 設置座標標記顏色
 
// 獲取折線對象
LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot
.getRenderer();
BasicStroke realLine = new BasicStroke(1.8f); // 設置實線
// 設置虛線
float dashes[] = { 5.0f };
BasicStroke brokenLine = new BasicStroke(2.2f, // 線條粗細
BasicStroke.CAP_ROUND, // 端點風格
BasicStroke.JOIN_ROUND, // 折點風格
8f, dashes, 0.6f);
 
plot.setNoDataMessage("無對應的數據,請從新查詢。");
plot.setNoDataMessagePaint(Color.RED);// 字體顏色
// 把餅圖生成圖片
String chartName = "";
FileOutputStream fos_jpg = null;
try {
// 文件夾不存在則建立
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
chartName = path + File.separator + new Date().getTime() + ".png";
fos_jpg = new FileOutputStream(chartName);
// 高寬的設置影響橢圓餅圖的形狀
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);
 
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos_jpg.close();// http://1wangxiaobo@163.com
} catch (Exception e) {
e.printStackTrace();
}
return chartName;
}
}
 
public static String createCategoryDataset(String title, String domainName,
String rangeName, DefaultCategoryDataset dataset, String path) {
JFreeChart chart = ChartFactory
.createBarChart(title, domainName, rangeName, dataset,
PlotOrientation.VERTICAL, true, true, false);
chart.getTitle().setFont((new Font("隸書", Font.CENTER_BASELINE, 20))); // 設置標題字體
CategoryPlot plot = chart.getCategoryPlot();// 得到圖表區域對象
// 設置圖表的縱軸和橫軸org.jfree.chart.axis.CategoryAxis
CategoryAxis domainAxis = plot.getDomainAxis();
NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
TextTitle textTitle = chart.getTitle();
textTitle.setFont(new Font("黑體", Font.PLAIN, 20));
domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));
domainAxis.setLabelFont(new Font("宋體", Font.PLAIN, 12));
numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
numberaxis.setLabelFont(new Font("黑體", Font.PLAIN, 12));
chart.getLegend().setItemFont(new Font("宋體", Font.PLAIN, 12));
 
String chartName = "";
FileOutputStream fos_jpg = null;
try {
// 文件夾不存在則建立
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
chartName = path + File.separator + new Date().getTime() + ".png";
fos_jpg = new FileOutputStream(chartName);
// 高寬的設置影響橢圓餅圖的形狀
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);
 
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos_jpg.close();// http://1wangxiaobo@163.com
} catch (Exception e) {
e.printStackTrace();
}
return chartName;
}
}
 
public static String createBarChart(String title, String domainName,
String rangeName, CategoryDataset dataset, String path) {
JFreeChart chart = ChartFactory.createBarChart3D(title,domainName ,
rangeName, dataset, PlotOrientation.VERTICAL, true, true, false);
CategoryPlot plot = chart.getCategoryPlot();
chart.getTitle().setFont((new Font("隸書", Font.CENTER_BASELINE, 20))); // 設置標題字體
// 設置網格背景顏色
plot.setBackgroundPaint(Color.white);
// 設置網絡豎線顏色
plot.setDomainGridlinePaint(Color.pink);
// 顯示每一個柱的數值,並修改該數字的字體屬性
BarRenderer3D renderer = new BarRenderer3D();
renderer
.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
// 默認的數字顯示在柱子中,經過如下兩句調整數字的顯示
// 注意,此句很關鍵,若無此句,那數字的顯示會覆蓋,給人數字沒有顯示出來的問題
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
renderer.setItemLabelAnchorOffset(10D);
// 設置每一個地區所包含的平行柱的之間的距離
// renderer.setItemMargin(0.3);
plot.setRenderer(renderer);
 
// 設置位置
plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
// 將默認的左邊的放到右方
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
CategoryAxis domainAxis = plot.getDomainAxis();
// 圖表標題
Font font = new Font("宋體", Font.BOLD, 16);
chart.setTitle(title); // 標題
 
// X軸亂碼
// X軸座標上的文字:
domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));
// X軸座標標題
domainAxis.setLabelFont(new Font("宋體", Font.PLAIN, 12));
// Y軸座標上的文字
numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
// Y軸座標標題
numberaxis.setLabelFont(new Font("黑體", Font.PLAIN, 12));
// 圖表底部亂碼
chart.getLegend().setItemFont(new Font("黑體", Font.PLAIN, 12));
String chartName = "";
FileOutputStream fos_jpg = null;
try {
// 文件夾不存在則建立
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
chartName = path + File.separator + new Date().getTime() + ".png";
fos_jpg = new FileOutputStream(chartName);
// 高寬的設置影響橢圓餅圖的形狀
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 700, 400);
 
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos_jpg.close();// http://1wangxiaobo@163.com
} catch (Exception e) {
e.printStackTrace();
}
return chartName;
}
}
public static String createPointChart(XYDataset xydataset,  String title, String domainName, String rangeName, String noDateMsg,  String path){
  
        JFreeChart jfreechart = ChartFactory.createScatterPlot(title,  
        domainName, rangeName, xydataset, PlotOrientation.VERTICAL, true, false,  
                false);  
        jfreechart.setBackgroundPaint(Color.white);  
        jfreechart.setBorderPaint(Color.GREEN);  
        jfreechart.setBorderStroke(new BasicStroke(1.5f));  
        jfreechart.getTitle().setFont((new Font("隸書", Font.CENTER_BASELINE, 20)));
        jfreechart.getLegend().setItemFont(new Font("隸書", Font.CENTER_BASELINE, 15));// 設置圖例類別字體
        
        XYPlot xyplot = (XYPlot) jfreechart.getPlot();  
        xyplot.setNoDataMessage(noDateMsg);  
        xyplot.setNoDataMessageFont(new Font("隸書", Font.BOLD, 14));  
        //xyplot.setNoDataMessagePaint(new Color(87, 149, 117));  
  
        xyplot.setBackgroundPaint(new Color(255, 253, 246));  
        ValueAxis vaaxis = xyplot.getDomainAxis();  
        vaaxis.setAxisLineStroke(new BasicStroke(1.5f));  
  
        ValueAxis va = xyplot.getDomainAxis(0);  
        va.setAxisLineStroke(new BasicStroke(1.5f));  
  
        va.setAxisLineStroke(new BasicStroke(1.5f)); // 座標軸粗細  
        va.setAxisLinePaint(new Color(215, 215, 215)); // 座標軸顏色  
        xyplot.setOutlineStroke(new BasicStroke(1.5f)); // 邊框粗細  
        va.setLabelPaint(new Color(10, 10, 10)); // 座標軸標題顏色  
        va.setTickLabelPaint(new Color(102, 102, 102)); // 座標軸標尺值顏色  
        ValueAxis axis = xyplot.getRangeAxis();  
        vaaxis.setLabelFont(new Font("隸書", Font.CENTER_BASELINE, 15));
        axis.setAxisLineStroke(new BasicStroke(1.5f));  
  
        XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot  
                .getRenderer();  
        xylineandshaperenderer.setSeriesOutlinePaint(0, Color.WHITE);  
        xylineandshaperenderer.setUseOutlinePaint(true);  
        NumberAxis numberaxis = (NumberAxis) xyplot.getDomainAxis();  
        numberaxis.setAutoRangeIncludesZero(false);  
        numberaxis.setTickMarkInsideLength(2.0F);  
        numberaxis.setTickMarkOutsideLength(0.0F);  
        numberaxis.setAxisLineStroke(new BasicStroke(1.5f));  
       // numberaxis.setUpperBound(maxpress); 最大值設置 
       // numberaxis.setLowerBound();最小值設置
        NumberAxis numberaxis1 = (NumberAxis) xyplot.getRangeAxis();  
        numberaxis1.setTickMarkInsideLength(2.0F);  
        numberaxis1.setTickMarkOutsideLength(0.0F);  
        numberaxis1.setUpperBound(150d);  
        numberaxis1.setLowerBound(35);  
        numberaxis1.setAxisLineStroke(new BasicStroke(1.5f));  
        numberaxis1.setLabelFont(new Font("隸書", Font.CENTER_BASELINE, 15));
  
        XYBoxAnnotation box = new XYBoxAnnotation(0, 0, 89, 59); //正常血壓所在區域內邊界  
        XYBoxAnnotation box1 = new XYBoxAnnotation(0, 0, 119, 79);//高血壓前期所在區域內邊界  
        XYBoxAnnotation box2 = new XYBoxAnnotation(0, 0, 139, 89);//高血壓一期所在區域內邊界  
        XYBoxAnnotation box3 = new XYBoxAnnotation(0, 0, 159, 99);//高血壓二期所在區域內邊界  
        XYTextAnnotation text1 = new XYTextAnnotation("nomal", 70, 62.5);//標識「正常」  
        XYTextAnnotation text = new XYTextAnnotation("fore", 70, 82.5);//「高血壓前期」  
        XYTextAnnotation text2 = new XYTextAnnotation("one", 70, 91.5);//「高血壓一期」  
        XYTextAnnotation text3 = new XYTextAnnotation("two", 70, 101.5);//「高血壓二期」  
  
          
        //將上面的邊界線條,說明文字加入到xyplot中。  
        xyplot.addAnnotation(box);  
        xyplot.addAnnotation(box1);  
        xyplot.addAnnotation(box2);  
        xyplot.addAnnotation(box3);  
  
        xyplot.addAnnotation(text);  
        xyplot.addAnnotation(text1);  
        xyplot.addAnnotation(text2);  
        xyplot.addAnnotation(text3);  
        String chartName = "";
FileOutputStream fos_jpg = null;
try {
// 文件夾不存在則建立
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
chartName = path + File.separator + new Date().getTime() + ".png";
fos_jpg = new FileOutputStream(chartName);
ChartUtilities.writeChartAsPNG(fos_jpg, jfreechart, 700, 400);
 
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos_jpg.close();// http://1wangxiaobo@163.com
} catch (Exception e) {
e.printStackTrace();
}
return chartName;
}
}
}
各類數據集格式說明:
3D餅圖:
String[] keys = { "王曉博", "李冰", "牛根生", "李開復", "馬雲", "其它" };
 double[] data = { 60, 60, 55, 77, 80, 50 };
 DefaultPieDataset dataset = new DefaultPieDataset();
 for (int i = 0; i < keys.length; i++) {
  dataset.setValue(keys[i], data[i]);
 }
 
 
 
折線圖:
      DefaultCategoryDataset ds = new DefaultCategoryDataset();  
ds.addValue(90, "溫度", "2011-01-01");
ds.addValue(100, "溫度", "2011-01-02");
ds.addValue(80, "溫度", "2011-01-03");
ds.addValue(120, "溫度", "2011-01-04");
ds.addValue(130, "溼度", "2011-01-01");
ds.addValue(100, "溼度", "2011-01-02");
ds.addValue(150, "溼度", "2011-01-03");
ds.addValue(140, "溼度", "2011-01-04");
柱狀圖:
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(100, "struts1.2", "張三");
dataset.addValue(200, "struts2.x", "張三");
dataset.addValue(300, "webwork", "張三");
dataset.addValue(400, "spring", "張三");
dataset.addValue(100, "struts1.2", "李四");
dataset.addValue(200, "struts2.x", "李四");
dataset.addValue(300, "webwork", "李四");
dataset.addValue(400, "spring", "李四");  //dataset.addValue(-20, "Ext JS", "Jan")負向座標
散點圖:
double[][] data1 = new double[2][5];
DefaultXYDataset xydataset = new DefaultXYDataset();  
data1[0][0] = 80;
data1[1][0] = 88;
data1[0][1] = 82;
data1[1][1] = 90;
data1[0][2] = 98;
data1[1][2] = 67;
data1[0][3] = 110;
data1[1][3] = 120;
data1[0][4] = 122;
data1[1][4] = 132;
xydataset.addSeries("溫度", data1); 
 
 
 
條形圖:
double[][] data = new double[][] { { 1310, 1220, 1110, 1000, 666 },
{ 720, 700, 680, 640, 777 }, { 1130, 1020, 980, 800, 888 },
{ 440, 400, 360, 300, 999 }, { 400, 400, 400, 400, 555 } };
String[] rowKeys = { "豬肉", "牛肉", "雞肉", "魚肉", "羊肉" };
String[] columnKeys = { "襄城", "樊城", "襄州", "東津", "魚梁州" };
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
rowKeys, columnKeys, data);
相關文章
相關標籤/搜索