import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.RingPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.RectangleEdge;
import com.growatt.oss.system.StaticParamUtils;
import aj.org.objectweb.asm.Type;
/**
* 生成圖工具
* @author Administrator
*
*/
public class JFreeChartUtils {
/**
* 環形圖
* @param charName 副标題
* @param charCount 總數
* @param dataset 資料集
* @param chartTitle 圖示題
* @param pieKeys 環形圖的名字集
* @param width 寬度
* @param height 高度
* @return
*/
public static String createAnnularChar(PieDataset dataset,
String chartTitle, String[] pieKeys, String charName,int width,int height){
JFreeChart chart = ChartFactory.createRingChart(chartTitle,dataset,true,true, false);
chart.setBorderVisible(false);
chart.setTextAntiAlias(false); // 使下說明标簽字型清晰,去鋸齒類似于
chart.setBackgroundPaint(Color.white); // 圖檔背景色
RingPlot ringplot=(RingPlot) chart.getPlot();
ringplot.setOutlineVisible(false); //坐标區表框是否顯示
ringplot.setBackgroundAlpha(0.8f);
//ringplot.setNoDataMessage("無對應的資料,請重新查詢。"); // 設定無資料時的資訊
ringplot.setNoDataMessagePaint(Color.red); // 設定無資料時的資訊顯示顔色
ringplot.setLabelFont(new Font("宋體", Font.BOLD, 15));
// 設定餅狀圖和環形圖的顯示數字。0代表顯示文字說明,1代表顯示數字,2代表顯示數字以百分比的方式如果多個結合{0}:{1}
ringplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{2}"));
ringplot.setBackgroundPaint(Color.white);//設定背景色
ringplot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({1})", NumberFormat.getNumberInstance(),
new DecimalFormat("0.00%"))); //設定圖例資料格式
ChartFrame mChartFrame = new ChartFrame("環形圖", chart);
mChartFrame.pack();
LegendTitle legendTitle = chart.getLegend();//獲得圖例标題
legendTitle.setPosition(RectangleEdge.RIGHT);//圖例右邊顯示
legendTitle.setBorder(0, 0, 0, 0);//設定圖例上下左右線
legendTitle.setPadding(0, 0, 0, 50);
// 設定圖示題的字型重新設定title
Font font = new Font("隸書", Font.BOLD, 25);
TextTitle title = new TextTitle(chartTitle);
title.setFont(font);
chart.setTitle(title);
if (charName != null) {
Font font2 = new Font("宋體", Font.BOLD, 15);
TextTitle title2 = new TextTitle(charName);
title2.setFont(font2);
chart.addSubtitle(title2);
}
FileOutputStream fos_jpg = null;
try{
String name = System.currentTimeMillis()+""+Math.round((Math.random()+1) * 1000)+".png";
// 檔案夾不存在則建立
String chartName = StaticParamUtils.COMMONFILEPATH + name;
fos_jpg = new FileOutputStream(chartName);
// 高寬的設定
ChartUtilities.writeChartAsPNG(fos_jpg, chart, width, height);
return chartName;
}
catch (Exception e){
e.printStackTrace();
return null;
}
finally{
try{
fos_jpg.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
/**
* 折線圖
* @param x x軸的說明(如種類,時間等)
* @param y y軸的說明(如速度,時間等)
* @param dataset 資料集
* @param chartTitle 圖示題
* @param pieKeys 環形圖的名字集
* @param width 寬度
* @param height 高度
* @param num y軸0.平放 1.傾斜45度 2.傾斜90度
* @param type num為不線上上顯示資料
* @return
*/
public static String createWireChar(int num,String type,String chartTitle, String x, String y,
CategoryDataset dataset,int width,int height){
JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y,
dataset, PlotOrientation.VERTICAL, false, true, false);
chart.setTextAntiAlias(false);
chart.setBackgroundPaint(Color.WHITE);
chart.setBorderVisible(false); //設定邊框是否可見
CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
categoryplot.setOutlinePaint(Color.WHITE);
ValueAxis valueAxis = categoryplot.getRangeAxis();
valueAxis.setAutoRange(true); //自動設定坐标值的間距
valueAxis.setAxisLineVisible(false);
LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();
lineandshaperenderer.setSeriesPaint(0,Color.blue); //設定每個分組的線的顔色
if (type!=null) {
// valueAxis.setVisible(false); 是否顯示y軸
// 獲得renderer 注意這裡是下嗍造型到lineandshaperenderer!!
lineandshaperenderer.setBaseShapesVisible(true); // series 點(即資料點)可見
lineandshaperenderer.setBaseLinesVisible(true); // series 點(即資料點)間有連線可見
lineandshaperenderer.setBaseItemLabelsVisible(true);
lineandshaperenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}%",NumberFormat.getNumberInstance()));
// 設定線條是否被顯示填充顔色
lineandshaperenderer.setUseFillPaint(true);
lineandshaperenderer.setBaseFillPaint(Color.blue);//藍色
}
// 設定面闆字型
Font labelFont = new Font("宋體",Font.BOLD, 12);
CategoryAxis domainAxis = categoryplot.getDomainAxis();
domainAxis.setLabelFont(labelFont);// 軸标題
domainAxis.setTickLabelFont(labelFont);// 軸數值
if (num == 0) {
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
}else if (num == 1) {
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
}else{
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
}
NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
numberaxis.setAutoRangeIncludesZero(true);
// numberaxis.setTickUnit(new NumberTickUnit(number)); //設定縱坐标值的間距為2
// 設定圖示題的字型重新設定title
Font font = new Font("隸書", Font.BOLD, 25);
TextTitle title = new TextTitle(chartTitle);
title.setFont(font);
chart.setTitle(title);
FileOutputStream fos_jpg = null;
try{
String name = System.currentTimeMillis()+""+Math.round((Math.random()+1) * 1000)+".png";
String chartName = StaticParamUtils.COMMONFILEPATH + name;
fos_jpg = new FileOutputStream(chartName);
// 将報表儲存為png檔案
ChartUtilities.writeChartAsPNG(fos_jpg, chart,width, height );
return chartName;
}
catch (Exception e){
e.printStackTrace();
return null;
}
finally{
try{
fos_jpg.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
* 柱狀圖
* @param num 0 平放顯示,1 45度顯示,2 90顯示
* @param type 是否顯示柱子上的值 為null表示不顯示
* @param width 寬度
* @param height 高度
* @param dataset 資料集
* @param x x軸的說明(如種類,時間等)
* @param y y軸的說明(如速度,時間等)
* @param chartTitle 圖示題
* @param charName 生成圖檔的名字
* @return
*/
public static String createPillarChart(int num,String type,CategoryDataset dataset, String x,String y,
String chartTitle,int width,int height){
JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 圖表标題
x,
y,
dataset,
PlotOrientation.VERTICAL,
false,
false,
false
);
Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
chart.setTextAntiAlias(false);
chart.setBackgroundPaint(Color.white);
CategoryPlot plot = chart.getCategoryPlot();
plot.setRangeGridlinesVisible(true);// 設定橫虛線可見
plot.setRangeGridlinePaint(Color.gray);// 虛線色彩
plot.setOutlinePaint(Color.WHITE); //邊框顔色
// 資料軸精度
NumberAxis vn = (NumberAxis) plot.getRangeAxis();
vn.setTickUnit(new NumberTickUnit(20));
DecimalFormat df = new DecimalFormat("#0.00");
vn.setNumberFormatOverride(df); // 資料軸資料标簽的顯示格式
// x軸設定
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(labelFont);// 軸标題
domainAxis.setTickLabelFont(labelFont);// 軸數值
if (num == 0) {
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
}else if (num == 1) {
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
}else{
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
}
domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 橫軸上的 Lable 是否完整顯示
domainAxis.setLowerMargin(0.1);// 設定距離圖檔左端距離
domainAxis.setUpperMargin(0.1);// 設定距離圖檔右端距離
plot.setDomainAxis(domainAxis);
plot.setBackgroundPaint(new Color(255, 255, 255)); // 設定柱圖背景色(注意,系統取色的時候要使用16位的模式來檢視顔色編碼,這樣比較準确)
BarRenderer renderer = new BarRenderer();
renderer.setSeriesPaint(0, new Color(100 ,149 ,237));//計劃柱子的顔色
renderer.setMaximumBarWidth(0.03); // 設定柱子寬度
renderer.setMinimumBarLength(0.2); // 設定柱子高度
renderer.setDrawBarOutline(false); // 設定柱子邊框可見
ValueAxis rangeAxis = plot.getRangeAxis();// y軸設定
rangeAxis.setLabelFont(labelFont);
rangeAxis.setTickLabelFont(labelFont);
rangeAxis.setUpperMargin(0.15); // 設定最高的一個 Item 與圖檔頂端的距離
rangeAxis.setLowerMargin(0.15); // 設定最低的一個 Item 與圖檔底端的距離
rangeAxis.setAxisLineVisible(false); //y軸線是否顯示
rangeAxis.setAutoRange(true); //是否自動設定資料軸資料範圍
if (type != null) {
// 顯示每個柱的數值,并修改該數值的字型屬性
rangeAxis.setVisible(false); //Y軸内容是否顯示
renderer.setIncludeBaseInRange(true);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
renderer.setAutoPopulateSeriesFillPaint(true);//自動填充柱狀體顔色
renderer.setItemMargin(0.3);
}
plot.setRangeAxis(rangeAxis);
plot.setRenderer(renderer);
plot.setForegroundAlpha(1.0f);// 設定柱的透明度
FileOutputStream fos_jpg = null;
try{
String name = System.currentTimeMillis()+""+Math.round((Math.random()+1) * 1000)+".png";
String chartName = StaticParamUtils.COMMONFILEPATH + name;
fos_jpg = new FileOutputStream(chartName);
ChartUtilities.writeChartAsPNG(fos_jpg, chart, width, height, true, 10);
return chartName;
}
catch (Exception e){
e.printStackTrace();
return null;
}
finally{
try{
fos_jpg.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
/**
* 餅圖
* @param dataset 資料集
* @param chartTitle 标題
* @param width 圖形寬度
* @param height 圖形高度
* @return
*/
public static String createPieChart(PieDataset dataset,String chartTitle,int width,int height){
JFreeChart chart = ChartFactory.createPieChart(chartTitle, // chart
// title
dataset,// data
true,// include legend
true, false);
chart.setBackgroundPaint(Color.WHITE); //設定外邊顔色
PiePlot plot = (PiePlot) chart.getPlot();
// 設定無資料時的資訊
plot.setNoDataMessage("無對應的資料,請重新查詢。");
// 設定無資料時的資訊顯示顔色
plot.setNoDataMessagePaint(Color.red);
// 圖例顯示百分比:自定義方式, {0} 表示選項, {1} 表示數值, {2} 表示所占比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}"));
plot.setLabelGenerator(null); //去掉圖形标簽
plot.setOutlinePaint(Color.WHITE); // 設定繪圖面闆外邊的填充顔色
plot.setShadowPaint(Color.WHITE); // 設定繪圖面闆陰影的填充顔色
LegendTitle legend = chart.getLegend(); //圖例邊框顔色
legend.setFrame(new BlockBorder(Color.WHITE)); //圖例邊框顔色
FileOutputStream fos_jpg = null;
try
{
// 檔案夾不存在則建立
String name = System.currentTimeMillis()+""+Math.round((Math.random()+1) * 1000)+".png";
String chartName = StaticParamUtils.COMMONFILEPATH + name;
fos_jpg = new FileOutputStream(chartName);
// 高寬的設定影響橢圓餅圖的形狀
ChartUtilities.writeChartAsPNG(fos_jpg, chart,width, height);
return chartName;
}
catch (Exception e){
e.printStackTrace();
return null;
}
finally{
try{
fos_jpg.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
// 環形圖 資料集
public static PieDataset getDataAnnularUtil(double[] data,String[] datadescription){
if (data != null && datadescription != null){
if (data.length == datadescription.length){
DefaultPieDataset dataset = new DefaultPieDataset();
for (int i = 0; i < data.length; i++){
dataset.setValue(datadescription[i],data[i]);
}
return dataset;
}
}
return null;
}
// 餅圖 資料集
public static PieDataset getDataPieSetByUtil(double[] data,
String[] datadescription){
if (data != null && datadescription != null){
if (data.length == datadescription.length){
DefaultPieDataset dataset = new DefaultPieDataset();
for (int i = 0; i < data.length; i++){
dataset.setValue(datadescription[i], data[i]);
}
return dataset;
}
}
return null;
}
//柱狀圖,折線圖 資料集
public static CategoryDataset getBarData(double[][] data, String[] rowKeys,String[] columnKeys){
return DatasetUtilities
.createCategoryDataset(rowKeys, columnKeys, data);
}
/**
* 判斷檔案夾是否存在,如果不存在則建立
* @param chartPath
*/
private static void isChartPathExist(String chartPath){
File file = new File(chartPath);
if (!file.exists()){
file.mkdirs();
}
}
}