记录jfreechart生成图片测试程,主要是为自己研究过之后的记录:)
折线图+柱状图
柱状图(堆叠)+折线图
获取饼状图
获取环形图
jar包下载地址:https://download.csdn.net/download/srying/11123104
pom.xml文件配置配置
jfree
jfreechart
1.0.19
jfree
jcommon
1.0.23
package com.zjhc.iiap.common;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.SystemColor;
import java.io.File;
//import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
//import java.text.NumberFormat;
import java.util.Locale;
//import org.apache.commons.lang.WordUtils;
import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
//import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
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.DatasetRenderingOrder;
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.renderer.category.StackedBarRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
//import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
//import org.jfree.data.general.PieDataset;
//import org.jfree.ui.RectangleEdge;
import org.jfree.ui.TextAnchor;
public class JFreeChartUtil2 {
/*public static void main(String[] args) {
DefaultCategoryDataset barDataSet = new DefaultCategoryDataset();
barDataSet.addValue(0.6, "评价人数", "1月");
barDataSet.addValue(0.9, "评价人数", "2月");
DefaultCategoryDataset lineDataSet = new DefaultCategoryDataset();
lineDataSet.addValue(0.2, "评分", "1月");
lineDataSet.addValue(0.5, "评分", "2月");
getPhoFilePathTest(barDataSet, lineDataSet, "test", true);
}*/
/**
* 获取生成图片数据源
* 折线图+柱状图
* @param barDataSet 柱状图数据
* @param lineDataSet 折线图数据
* @param fileName 数据文件名称
* @param isPer0 第一个是否使用百分比刻度 true使用,false 不使用
* @param isPer1 第二个是否使用百分比刻度 true使用,false 不使用
* @param title 图片标题
* @return
*/
@SuppressWarnings("deprecation")
private static void getPhoFilePathTest(DefaultCategoryDataset barDataSet, DefaultCategoryDataset lineDataSet, String fileName, boolean isPer){
//创建主题样式 ,以下代码用于解决中文乱码问题
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);
// 柱状图数据源
// DefaultCategoryDataset barDataSet = new DefaultCategoryDataset();
// barDataSet.addValue(800, "评价人数", "1月");
// barDataSet.addValue(600, "评价人数", "2月");
//
// //折线图数据源
// DefaultCategoryDataset lineDataSet = new DefaultCategoryDataset();
// lineDataSet.addValue(5, "评分", "1月");
// lineDataSet.addValue(4, "评分", "4月");
BarRenderer barRender = new BarRenderer();
//展示柱状图数值
barRender.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
barRender.setBaseItemLabelsVisible(true);
barRender.setBasePositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE1, TextAnchor.BASELINE_CENTER));
//最短的BAR长度,避免数值太小而显示不出
barRender.setMinimumBarLength(0.5);
// 设置柱形图上的文字偏离值
barRender.setItemLabelAnchorOffset(10D);
//设置柱子的最大宽度
barRender.setMaximumBarWidth(0.03);
barRender.setItemMargin(0.000000005); // 设置柱状图之间的距离0.1代表10%
barRender.setBarPainter(new StandardBarPainter());//设置柱子为平面图不是立体的
barRender.setSeriesPaint(0,new Color(65,105,225)); // 给series1 Bar
barRender.setShadowVisible(false); //不显示阴影
barRender.setItemLabelAnchorOffset(3D);
if(isPer){
barRender.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",
DecimalFormat.getPercentInstance()));// //大括号内为0,显示s
barRender.setItemLabelsVisible(true);
}
LineAndShapeRenderer lineRender = new LineAndShapeRenderer();
//展示折线图节点值
lineRender.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
lineRender.setBaseItemLabelsVisible(true);
lineRender.setBasePositiveItemLabelPosition(
new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
// 设置折线图上的文字偏离值
lineRender.setItemLabelAnchorOffset(8D);
BasicStroke brokenLine = new BasicStroke(2f,//线条粗细
BasicStroke.CAP_SQUARE, //端点风格
BasicStroke.JOIN_MITER, //折点风格
8.f, //折点处理办法 ,如果要实线把该参数设置为NULL
new float[]{8.0f }, //虚线数组
0.0f);
//设置第一条折线的风格
lineRender.setSeriesStroke(0,brokenLine);
CategoryPlot plot = new CategoryPlot();
plot.setDataset(0, barDataSet);
plot.setDataset(1, lineDataSet);
plot.setRenderer(0, barRender);
plot.setRenderer(1, lineRender);
plot.setDomainAxis(new CategoryAxis());
//设置水平方向背景线颜色
plot.setRangeGridlinePaint(Color.gray);
//设置是否显示水平方向背景线,默认值为true
plot.setRangeGridlinesVisible(true);
//设置垂直方向背景线颜色
plot.setDomainGridlinePaint(Color.gray);
//设置是否显示垂直方向背景线,默认值为true
plot.setDomainGridlinesVisible(true);
//设置图表透明图0.0~1.0范围。0.0为完全透明,1.0为完全不透明。
plot.setForegroundAlpha(0.7F);
NumberAxis vn = new NumberAxis();
DecimalFormat df = new DecimalFormat("0.00%");
if(isPer){
vn.setUpperBound(1);
// 设置数据轴坐标从0开始
vn.setAutoRangeIncludesZero(true);
vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式
}
plot.setRangeAxis(vn);
NumberAxis vn2 = new NumberAxis();
if(isPer){
vn2.setUpperBound(1);
// 设置数据轴坐标从0开始
vn2.setAutoRangeIncludesZero(true);
vn2.setNumberFormatOverride(df); // 数据轴数据标签的显示格式
}
//设置Y轴刻度
plot.setRangeAxis(1, vn2);
// 设置折线图数据源应用Y轴右侧刻度
plot.mapDatasetToRangeAxis(1, 1);
for (int i = 0; i < plot.getRangeAxisCount(); i++)
{
ValueAxis rangeAxis = plot.getRangeAxis(i);
//设置最高的一个柱与图片顶端的距离
rangeAxis.setUpperMargin(0.25);
}
CategoryAxis categoryAxis = plot.getDomainAxis();
//X轴分类标签以45度倾斜
categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
JFreeChart chart = new JFreeChart(plot);
chart.setTitle("汽车口碑排行榜");
chart.setBackgroundPaint(SystemColor.WHITE);
ChartFrame chartFrame=new ChartFrame("汽车口碑排行榜",chart);
//以合适的大小展现图形
chartFrame.pack();
//图形是否可见
chartFrame.setVisible(true);
// String path = System.getProperty("user.dir") + File.separator + "template" + File.separator;
// String filePath = path+ fileName +".png";
// //图片名称
// File file = new File(filePath);
// try {
// ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return filePath;
}
//----------------------------------------------------------------------------------------------------------------------
/*public static void main(String[] args) {
double[] forwardItems = {12,34,45};//转发量
double[] commentItems = {24,14,35};//评论量
double[] seeItems = {32,24,25};//查看量
String[] items = { "微博", "微信", "测试" };
String[] series = new String[] { "转发", "评论", "查看" };
double[][] data = new double[][] { forwardItems, commentItems, seeItems };
CategoryDataset barDataset = DatasetUtilities.createCategoryDataset(series, items, data);
DefaultCategoryDataset lineDataset = new DefaultCategoryDataset();
lineDataset.addValue(10, "文章数", items[0]);
lineDataset.addValue(20, "文章数", items[1]);
lineDataset.addValue(30, "文章数", items[2]);
getPhoFilePathYulun(barDataset, lineDataset, "图片标题", "pubOpinion");
}*/
/**
*
* 柱状图(堆叠)+折线图
* @param categoryBarDataset 柱状图数据
* @param categoryLineDataset 折线图数据
* @param title 图片标题
* @return
*/
public static String getPhoFilePathYulun(CategoryDataset categoryBarDataset, CategoryDataset categoryLineDataset, String title,String fileName){
JFreeChart chart = createCharts(categoryBarDataset,categoryLineDataset, title);
// 处理主标题的乱码
chart.getTitle().setFont(new Font("黑体", Font.BOLD, 18));
chart.getLegend().setItemFont(new Font("黑体",Font.BOLD,10));//图例文字
// 获取图表区域对象
CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
// 获取X轴的对象
CategoryAxis categoryAxis = (CategoryAxis) categoryPlot.getDomainAxis();
categoryAxis.setLabelFont(new Font("黑体", Font.BOLD, 10));
categoryAxis.setTickLabelFont(new Font("黑体", Font.BOLD, 10));
// 获取Y轴的对象
NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
// 处理X轴上的乱码
categoryAxis.setTickLabelFont(new Font("黑体", Font.BOLD, 10));
// 处理X轴外的乱码
categoryAxis.setLabelFont(new Font("黑体", Font.BOLD, 10));
// 处理Y轴上的乱码
numberAxis.setTickLabelFont(new Font("黑体", Font.BOLD, 10));
// 处理Y轴外的乱码
numberAxis.setLabelFont(new Font("黑体", Font.BOLD, 10));
/*String path = System.getProperty("user.dir") + File.separator + "template" + File.separator;
String filePath = path + fileName + ".png";
File file = new File(filePath);
try {
ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
return filePath;*/
ChartFrame chartFrame=new ChartFrame("汽车口碑排行榜",chart);
//以合适的大小展现图形
chartFrame.pack();
//图形是否可见
chartFrame.setVisible(true);
return fileName;
}
/**
* 初始化
* @param categoryBarDataset
* @param categoryLineDataset
* @return
*/
private static JFreeChart createCharts(CategoryDataset categoryBarDataset, CategoryDataset categoryLineDataset, String title) {
//参数: title,x轴说明,y轴说明,图例
JFreeChart chart = ChartFactory.createBarChart(title, "", "", categoryBarDataset, PlotOrientation.VERTICAL,
true, true, true);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
// set right margin
plot.getDomainAxis().setUpperMargin(0.1);
// set X axis Label lines
plot.getDomainAxis().setMaximumCategoryLabelLines(2);
//NumberAxis na = (NumberAxis) plot.getRangeAxis();
// stack bar chart
StackedBarRenderer rederer = new StackedBarRenderer();
plot.setRenderer(0, rederer);
rederer.setBaseItemLabelsVisible(true);
rederer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
rederer.setBaseItemLabelFont(new Font("Calibri", Font.ITALIC, 15));
rederer.setMaximumBarWidth(0.07);
rederer.setMinimumBarLength(0.1);
rederer.setBarPainter(new StandardBarPainter());
rederer.setSeriesPaint(0, new Color(65,105,225));
rederer.setSeriesPaint(1, new Color(203,196,52));
rederer.setSeriesPaint(2, new Color(128,7,248));
// line chart
LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
plot.setRenderer(1, lineRenderer);
lineRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
lineRenderer.setBaseItemLabelFont(new Font("Calibri", Font.ITALIC, 15));
lineRenderer.setBasePositiveItemLabelPosition(
new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.BASELINE_LEFT));
lineRenderer.setBaseItemLabelsVisible(true);
lineRenderer.setBaseShapesVisible(true);
// point style
lineRenderer.setSeriesShape(0, new Rectangle(5, 5));
lineRenderer.setBaseShapesVisible(true);
NumberAxis rightYAxis = new NumberAxis("");
rightYAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
plot.setRangeAxis(1, rightYAxis);
plot.setDataset(1, categoryLineDataset);
plot.mapDatasetToRangeAxis(1, 1);
// set render order
plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
return chart;
}
//----------------------------------------------------------------------------------------------------------------------
//参考 https://blog.csdn.net/xiaowanziwuha/article/details/77828693
/*public static void main(String[] args) {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("男", new Double(20));
dataset.setValue("女", new Double(20));
dataset.setValue("其他", new Double(40));
getPhoFilePathPie(dataset, "图片标题");
}*/
/**
* 获取饼状图
*
* @return
*/
public static String getPhoFilePathPie(DefaultPieDataset dataset, String chartTitle){
/*DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("男", new Double(20));
dataset.setValue("女", new Double(20));
dataset.setValue("其他", new Double(40));*/
JFreeChart chart = ChartFactory.createPieChart(chartTitle, // chartTitle
dataset, // data
true, // include legend
true, false);
setChart(chart);
PiePlot pieplot = (PiePlot) chart.getPlot();
//设置颜色,可以删除
pieplot.setSectionPaint("男", Color.decode("#6495ED"));
pieplot.setSectionPaint("女", Color.decode("#F4A460"));
pieplot.setSectionPaint("其他", Color.decode("#FFDEAD"));
pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1}人)/{2}"));
//设置标签字体
pieplot.setLabelFont(new Font("宋体", 0, 12));
//设置图例项目字体
chart.getLegend().setItemFont(new Font("宋体", 0, 12));
/* String path = "e:\\test\\PieChart2.png";
try {
// 保存图片到指定文件夹
ChartUtilities.saveChartAsPNG(new File(path), chart, 1000, 700);
System.err.println("成功");
} catch (Exception e) {
System.err.println("创建图形时出错");
}
return path;*/
ChartFrame chartFrame=new ChartFrame("汽车口碑排行榜",chart);
//以合适的大小展现图形
chartFrame.pack();
//图形是否可见
chartFrame.setVisible(true);
return chartTitle;
}
/**
* 初始化
* @param chart
*/
public static void setChart(JFreeChart chart) {
chart.setTextAntiAlias(true);
PiePlot pieplot = (PiePlot) chart.getPlot();
// 设置图表背景颜色
pieplot.setBackgroundPaint(ChartColor.WHITE);
pieplot.setLabelBackgroundPaint(null);// 标签背景颜色
pieplot.setLabelOutlinePaint(null);// 标签边框颜色
pieplot.setLabelShadowPaint(null);// 标签阴影颜色
pieplot.setOutlinePaint(null); // 设置绘图面板外边的填充颜色
pieplot.setShadowPaint(null); // 设置绘图面板阴影的填充颜色
pieplot.setSectionOutlinesVisible(false);
pieplot.setNoDataMessage("没有可供使用的数据!");
}
public static void main(String[] args) {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("1.0分-2.0分", new Double(100));
dataset.setValue("2.0分-3.0分", new Double(10));
dataset.setValue("3.0分-4.0分", new Double(30));
dataset.setValue("4.0分-5.0分", new Double(40));
dataset.setValue("5.0分-6.0分", new Double(80));
dataset.setValue("6.0分-7.0分", new Double(60));
dataset.setValue("7.0分-8.0分", new Double(50));
dataset.setValue("8.0分-9.0分", new Double(20));
//保存为图片
//createRingChart(dataset,"title","test");
//运行为java输出图片
final ChartFrame frame = new ChartFrame("Interval Bar Chart Demo", createRingChart(dataset,"title","test"));
frame.pack();
frame.setVisible(true);
}
/**
* 获取环形图
*
* 参考:https://blog.csdn.net/u014315941/article/details/50802800
* @param dataset
* @param 图片标题
* @param 生成图片名称
* @return
*/
public static JFreeChart createRingChart(DefaultPieDataset dataset,String title, String fileName) {
JFreeChart chart5 = ChartFactory.createRingChart(title, dataset, true, true,
Locale.CHINESE);
setRingChart(chart5);
//保存为图片
/*String path = System.getProperty("user.dir") + File.separator + "template" + File.separator;
String filePath = path+ fileName+".png";
//图片名称
File file = new File(filePath);
try {
ChartUtilities.saveChartAsJPEG(file, chart5, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}*/
//return filePath;
return chart5;
}
/**
*
* @param chart
*/
@SuppressWarnings("deprecation")
public static void setRingChart(JFreeChart chart) {
chart.setBackgroundPaint(Color.white);
RingPlot ringplot = (RingPlot) chart.getPlot();
ringplot.setLabelBackgroundPaint(Color.WHITE);
ringplot.setSectionPaint(0, new Color(255,192,203));
ringplot.setSectionPaint(1, new Color(100,149,237));
ringplot.setSectionPaint(2, new Color(152,251,152));
ringplot.setSectionPaint(3, new Color(151,210,205));
ringplot.setSectionPaint(4, new Color(220,220,220));
ringplot.setSectionPaint(5, new Color(236,150,79));
ringplot.setSectionPaint(6, new Color(191,179,64));
ringplot.setSectionPaint(7, new Color(211,176,238));
// ringplot.setLabelLinksVisible(false);
// 设置饼状图和环形图的显示数字。0代表显示文字说明,1代表显示数字,2代表显示数字以百分比的方式如果多个结合{0}:{1}
ringplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{2}"));
ringplot.setSimpleLabels(true);
ringplot.setLabelBackgroundPaint(new Color(1.0F, 0.75F, 0.0F, 0.0F));
ringplot.setLabelFont(new Font("sans-serif", Font.PLAIN, 12));
ringplot.setLabelOutlinePaint(new Color(1.0F, 0.75F, 0.0F, 0.0F));
ringplot.setLabelPaint(Color.white);
ringplot.setLabelFont(new Font("微软雅黑", Font.PLAIN, 16));
ringplot.setLabelShadowPaint(new Color(1.0F, 0.75F, 0.0F, 0.0F));
TextTitle title = chart.getTitle();
title.setFont(new Font("sans-serif", Font.PLAIN, 24));
// 设置深度,即带颜色圆环的宽度
ringplot.setSectionDepth(0.5d);
// 设置环形图背景颜色
ringplot.setBackgroundPaint(Color.white);
chart.getLegend().setItemFont(new Font("微软雅黑", Font.BOLD, 12));
}
}