目录
1、添加依赖
2、生成图表图片工具类
3、调用测试生成对应的图片
4、生成的图片示例
4.1 饼图
4.2 折线图
4.3 柱状图
4.4 折线图-多条
4.5 生成3D柱状图
4.6 生成气泡图
4.7 生成时序图
1、添加依赖
jfree
jcommon
1.0.16
jfree
jfreechart
1.0.13
2、生成图表图片工具类
package com.shucha.deveiface.biz.test;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.jfree.chart.ChartFactory;
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.NumberAxis;
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.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.DefaultXYZDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
import java.util.Map;
public class JfreeChartUtils {
// 参考文章 https://www.jianshu.com/p/6c4f3832c396
public static String imagePath = "D://123//jfree";
public static void main(String[] args) throws Exception {
// 生成饼图
testPie();
// 生成折线图
testLine();
// 生成柱状图
testBar();
// 生成折线图 多条
testCreateManyLineChart();
// 生成3D柱状图
bar3D();
// 生成气泡图
bubble();
// 生成时序图
sequenceDiagram();
}
public static void testPie(){
//如 果不使用Font,中文将显示不出来
Font font = new Font("新宋体", Font.BOLD, 15);
// 创建数据:饼状图就是名称和值(比例)
Map map=new HashMap();
map.put("录播主机", (double) 1000);
map.put("编码器", (double) 700);
map.put("摄像机", (double) 600);
map.put("流转码服务器", (double) 400);
map.put("腾讯服务器", (double) 150);
// 创建JFreeChart
JFreeChart chart = createPieChart("故障设备类型比例", map, font);
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_饼图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testLine(){
//如 果不使用Font,中文将显示不出来
Font font = new Font("新宋体", Font.BOLD, 15);
// 创建数据
Map> datas =new HashMap>();
Map map1=new HashMap();
Map map2=new HashMap();
Map map3=new HashMap();
Map map4=new HashMap();
Map map5=new HashMap();
Map map6=new HashMap();
Map map7=new HashMap();
Map map8=new HashMap();
map1.put("故障数量", (double) 20);
map2.put("故障数量", (double) 30);
map3.put("故障数量", (double) 25);
map4.put("故障数量", (double) 50);
map5.put("故障数量", (double) 40);
map6.put("故障数量", (double) 25);
map7.put("故障数量", (double) 50);
map8.put("故障数量", (double) 40);
//压入数据
datas.put("一月", map1);
datas.put("二月", map2);
datas.put("三月", map3);
datas.put("四月", map4);
datas.put("五月", map5);
datas.put("六月", map6);
datas.put("七月", map7);
datas.put("八月", map8);
JFreeChart chart = createLineChart("故障数量-时间曲线", datas, "月份", "故障次数(次)", font);
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_折线图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testBar(){
//如 果不使用Font,中文将显示不出来
Font font = new Font("新宋体", Font.BOLD, 15);
// 创建数据
Map> datas =new HashMap>();
Map map1=new HashMap();
Map map2=new HashMap();
Map map3=new HashMap();
map1.put("故障数", (double) 1000);
map2.put("故障数", (double) 1300);
map3.put("故障数", (double) 1000);
//压入数据
datas.put("设备网络掉线", map1);
datas.put("CPU利用率高", map2);
datas.put("磁盘占用高", map3);
datas.put("掉线频率", map3);
datas.put("内存使用率", map2);
datas.put("访问量", map1);
JFreeChart chart = createBarChart("故障类型比例",datas,"故障类型","数量单位(个)",font);
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_柱状图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testCreateManyLineChart(){
String[] title = {"成功量","失败量","异常"};
String[] xValue = {"2021-01","2021-02","2021-03","2021-04","2021-05"};
// 绘图数据集
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
Random r = new Random();
for (int i =0;i> param) {
TreeMap> paramTreeMap = new TreeMap<>(param);
System.out.println(paramTreeMap);
}
public static JFreeChart createPieChart(String title, Map data, Font font) {
try {
Set> set = data.entrySet();
DefaultPieDataset pds = new DefaultPieDataset();
Iterator iterator = set.iterator();
Map.Entry entry;
while (iterator.hasNext()) {
entry = (Map.Entry) iterator.next();
pds.setValue(entry.getKey().toString(), Double.parseDouble(entry.getValue().toString()));
}
// 生成一个饼图的图表:显示图表的标题、组装的数据、是否显示图例、是否生成贴士以及是否生成URL链接
JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, true);
// 设置图片标题的字体
chart.getTitle().setFont(font);
// 得到图块,准备设置标签的字体
PiePlot plot = (PiePlot) chart.getPlot();
//设置分裂效果,需要指定分裂出去的key
// plot.setExplodePercent("摄像机", 0.1); 分裂效果,可选
// 设置标签字体
plot.setLabelFont(font);
// 设置图例项目字体
chart.getLegend().setItemFont(font);
// 设置开始角度
// plot.setStartAngle(new Float(3.14f / 2f)); 开始角度,意义不大
//设置plot的前景色透明度
plot.setForegroundAlpha(0.7f);
//设置plot的背景色透明度
plot.setBackgroundAlpha(0.0f);
//设置标签生成器(默认{0})
//{0}:key {1}:value {2}:百分比 {3}:sum
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}")); // 一般在{1}后面加单位,如:{0}({1}次)/{2}
//将内存中的图片写到本地硬盘
// ChartUtilities.saveChartAsJPEG(new File("H:/a.png"), chart, 600, 300);
return chart;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static JFreeChart createLineChart(String title, Map> data, String type, String unit, Font font) {
try {
DefaultCategoryDataset ds = new DefaultCategoryDataset();
Set>> set1 = data.entrySet();
Iterator iterator1 = set1.iterator();
Iterator iterator2;
HashMap map;
Set> set2;
Map.Entry entry1;
Map.Entry entry2;
while (iterator1.hasNext()) {
entry1 = (Map.Entry) iterator1.next();
map = (HashMap) entry1.getValue();
set2 = map.entrySet();
iterator2 = set2.iterator();
while (iterator2.hasNext()) {
entry2 = (Map.Entry) iterator2.next();
ds.setValue(Double.parseDouble(entry2.getValue().toString()), entry2.getKey().toString(), entry1.getKey().toString());
}
}
//创建折线图,折线图分水平显示和垂直显示两种
// //2D折线图
JFreeChart chart = ChartFactory.createLineChart(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, true);
// //3D折线图
JFreeChart chart2 = ChartFactory.createLineChart3D(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, false);
//设置整个图片的标题字体
chart.getTitle().setFont(font);
//设置提示条字体
font = new Font("宋体", Font.BOLD, 15);
chart.getLegend().setItemFont(font);
//得到绘图区
CategoryPlot plot = (CategoryPlot) chart.getPlot();
//得到绘图区的域轴(横轴),设置标签的字体
plot.getDomainAxis().setLabelFont(font);
// 设置背景透明度
plot.setBackgroundAlpha(0.1f);
// 设置网格横线颜色
plot.setRangeGridlinePaint(Color.gray);
// 设置网格横线大小
plot.setDomainGridlineStroke(new BasicStroke(0.2F));
plot.setRangeGridlineStroke(new BasicStroke(0.2F));
//设置横轴标签项字体
plot.getDomainAxis().setTickLabelFont(font);
// 生成折线图上的数字
//绘图区域(红色矩形框的部分)
LineAndShapeRenderer lineAndShapeRenderer=(LineAndShapeRenderer)plot.getRenderer();
lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
//设置图表上的数字可见
lineAndShapeRenderer.setBaseItemLabelsVisible(true);
//设置图表上的数字字体
lineAndShapeRenderer.setBaseItemLabelFont(new Font("宋体",Font.BOLD,15));
//设置折线图拐角上的正方形
//创建一个正方形
Rectangle shape=new Rectangle(4,4);
lineAndShapeRenderer.setSeriesShape(0, shape);
//设置拐角上图形可见
lineAndShapeRenderer.setSeriesShapesVisible(0, true);
//设置范围轴(纵轴)字体
font = new Font("宋体", Font.BOLD, 18);
plot.getRangeAxis().setLabelFont(font);
// plot.setForegroundAlpha(1.0f);
return chart;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static JFreeChart createManyLineChart(DefaultCategoryDataset dataSet){
//如果把createLineChart改为createLineChart3D就变为了3D效果的折线图
JFreeChart chart = ChartFactory.createLineChart("图表标题", "X轴标题", "Y轴标题", dataSet,
PlotOrientation.VERTICAL, // 绘制方向
true, // 显示图例
true, // 采用标准生成器
false // 是否生成超链接
);
//如 果不使用Font,中文将显示不出来
Font font = new Font("新宋体", Font.BOLD, 15);
chart.getTitle().setFont(font); // 设置标题字体
chart.getLegend().setItemFont(font);// 设置图例类别字体
// chart.setBackgroundPaint();// 设置背景色
//获取绘图区对象
CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.LIGHT_GRAY); // 设置绘图区背景色
plot.setRangeGridlinePaint(Color.gray); // 设置水平方向背景线颜色
// 设置背景透明度
plot.setBackgroundAlpha(0.1f);
// 设置网格横线颜色
plot.setRangeGridlinePaint(Color.gray);
// 设置网格横线大小
plot.setDomainGridlineStroke(new BasicStroke(0.2F));
plot.setRangeGridlineStroke(new BasicStroke(0.2F));
plot.setRangeGridlinesVisible(true);// 设置是否显示水平方向背景线,默认值为true
plot.setDomainGridlinePaint(Color.WHITE); // 设置垂直方向背景线颜色
plot.setDomainGridlinesVisible(true); // 设置是否显示垂直方向背景线,默认值为false
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(font); // 设置横轴字体
domainAxis.setTickLabelFont(font);// 设置坐标轴标尺值字体
domainAxis.setLowerMargin(0.01);// 左边距 边框距离
domainAxis.setUpperMargin(0.06);// 右边距 边框距离,防止最后边的一个数据靠近了坐标轴。
domainAxis.setMaximumCategoryLabelLines(2);
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(font);
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);
for (int i = 0; i < dataSet.getRowCount(); i++) {
if (i % 2 == 0) {
renderer.setSeriesStroke(i, realLine); // 利用实线绘制
} else {
renderer.setSeriesStroke(i, brokenLine); // 利用虚线绘制
}
// 生成折线图上的数字
//绘图区域(红色矩形框的部分)
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
//设置图表上的数字可见
renderer.setBaseItemLabelsVisible(true);
//设置图表上的数字字体
renderer.setBaseItemLabelFont(new Font("宋体",Font.BOLD,15));
//设置折线图拐角上的正方形
//创建一个正方形
Rectangle shape=new Rectangle(4,4);
renderer.setSeriesShape(0, shape);
//设置拐角上图形可见
renderer.setSeriesShapesVisible(0, true);
}
plot.setNoDataMessage("无对应的数据,请重新查询。");
plot.setNoDataMessageFont(font);//字体的大小
plot.setNoDataMessagePaint(Color.RED);//字体颜色
return chart;
}
public static JFreeChart createBarChart(String title,Map> data,String type,String danwei,Font font){
try {
//种类数据集
DefaultCategoryDataset ds = new DefaultCategoryDataset();
//获取迭代器:
Set>> set1 = data.entrySet();
Iterator iterator1= set1.iterator();
Iterator iterator2;
HashMap map;
Set> set2;
Map.Entry entry1;
Map.Entry entry2;
while(iterator1.hasNext()){
entry1=(Map.Entry) iterator1.next();
map=(HashMap) entry1.getValue();
set2=map.entrySet();
iterator2=set2.iterator();
while (iterator2.hasNext()) {
entry2= (Map.Entry) iterator2.next();
ds.setValue(Double.parseDouble(entry2.getValue().toString()), entry2.getKey().toString(), entry1.getKey().toString());
}
}
//创建柱状图,柱状图分水平显示和垂直显示两种
JFreeChart chart = ChartFactory.createBarChart(title, type, danwei, ds, PlotOrientation.VERTICAL, true, true, true);
//设置整个图片的标题字体
chart.getTitle().setFont(font);
//设置提示条字体
font = new Font("宋体", Font.BOLD, 15);
chart.getLegend().setItemFont(font);
//得到绘图区
CategoryPlot plot = (CategoryPlot) chart.getPlot();
//得到绘图区的域轴(横轴),设置标签的字体
plot.getDomainAxis().setLabelFont(font);
//获取X轴的对象
// CategoryAxis categoryAxis = plot.getDomainAxis();
// 设置X轴文本倾斜45度
// categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
// 设置背景透明度
plot.setBackgroundAlpha(0.1f);
// 设置网格横线颜色
plot.setRangeGridlinePaint(Color.gray);
// 设置网格横线大小
plot.setDomainGridlineStroke(new BasicStroke(0.2F));
plot.setRangeGridlineStroke(new BasicStroke(0.2F));
//设置横轴标签项字体
plot.getDomainAxis().setTickLabelFont(font);
// 设置柱状图柱子相关
CategoryPlot categoryPlot = chart.getCategoryPlot();
BarRenderer rendererBar = (BarRenderer) categoryPlot.getRenderer();
// 柱子宽度
rendererBar.setMaximumBarWidth(0.05);
// 柱状图颜色
rendererBar.setSeriesPaint(0, Color.decode("#005AB5"));
//设置范围轴(纵轴)字体
plot.getRangeAxis().setLabelFont(font);
plot.setForegroundAlpha(1.0f);
return chart;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void bar3D() {
final String fait = "菲亚特";
final String audi = "奥迪";
final String ford = "福特";
final String speed = "速度";
final String popular = "喜欢程度";
final String mailage = "邮寄";
final String userrating = "用户评价";
final String safty = "安全性";
final DefaultCategoryDataset dataset = new DefaultCategoryDataset( );
dataset.addValue( 1.0 , fait , speed );
dataset.addValue( 4.0 , fait , popular );
dataset.addValue( 3.0 , fait , userrating );
dataset.addValue( 5.0 , fait , mailage );
dataset.addValue( 5.0 , fait , safty );
dataset.addValue( 5.0 , audi , speed );
dataset.addValue( 7.0 , audi , popular );
dataset.addValue( 6.0 , audi , userrating );
dataset.addValue( 10.0 , audi , mailage );
dataset.addValue( 4.0 , audi , safty );
dataset.addValue( 4.0 , ford , speed );
dataset.addValue( 3.0 , ford , popular );
dataset.addValue( 2.0 , ford , userrating );
dataset.addValue( 3.0 , ford , mailage );
dataset.addValue( 6.0 , ford , safty );
// 设置字体,去除中文乱码
StandardChartTheme sct = new StandardChartTheme("CN");
sct.setExtraLargeFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));
sct.setRegularFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));
sct.setLargeFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));
ChartFactory.setChartTheme(sct);
JFreeChart chart = ChartFactory.createBarChart3D(
"汽车使用统计",
"类别",
"值",
dataset,
PlotOrientation.VERTICAL,
true, true, false);
// 注释的代码放开就是背景透明
int width = 640;
int height = 480;
// 标注位于上侧
chart.getLegend().setPosition(RectangleEdge.TOP);
// 设置标注无边框
chart.getLegend().setFrame(new BlockBorder(Color.WHITE));
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_3D柱状图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void bubble() {
DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset( );
double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 };
double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 };
double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 };
double ad3[ ][ ] = { ad , ad1 , ad2 };
defaultxyzdataset.addSeries( "系统1" , ad3 );
JFreeChart jfreechart = ChartFactory.createBubbleChart(
"年龄、体重和工作",
"重量",
"年龄",
defaultxyzdataset,
PlotOrientation.HORIZONTAL,
true, true, false);
XYPlot xyplot = ( XYPlot )jfreechart.getPlot();
xyplot.setForegroundAlpha( 0.65F );
XYItemRenderer xyitemrenderer = xyplot.getRenderer( );
xyitemrenderer.setSeriesPaint( 0 , Color.blue );
NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( );
numberaxis.setLowerMargin( 0.2 );
numberaxis.setUpperMargin( 0.5 );
NumberAxis numberAxis = ( NumberAxis )xyplot.getRangeAxis( );
numberAxis.setLowerMargin( 0.8 );
numberAxis.setUpperMargin( 0.9 );
// 注释的代码是设置背景透明度
int width = 560;
int height = 370;
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_气泡图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, jfreechart, width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sequenceDiagram(){
final TimeSeries series = new TimeSeries( "Random Data" );
Second current = new Second();
double value = 100.0;
for ( int i = 0 ; i < 4000 ; i++ )
{
try {
value = value + Math.random( ) - 0.5;
series.add( current , new Double( value ) );
current = ( Second ) current.next( );
} catch ( SeriesException e ) {
System.err.println( "Error adding to series" );
}
}
final XYDataset dataset=( XYDataset )new TimeSeriesCollection(series);
JFreeChart timeChart = ChartFactory.createTimeSeriesChart(
"计算测试",
"秒数",
"值",
dataset,
false,
false,
false);
// 注释的代码是设置背景透明度
int width = 560;
int height = 370;
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_时序图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, timeChart, width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、调用测试生成对应的图片
public static void main(String[] args) throws Exception {
// 生成饼图
testPie();
// 生成折线图
testLine();
// 生成柱状图
testBar();
// 生成折线图 多条
testCreateManyLineChart();
// 生成3D柱状图
bar3D();
// 生成气泡图
bubble();
// 生成时序图
sequenceDiagram();
}
4、生成的图片示例
4.1 饼图
package com.shucha.deveiface.biz.test;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.jfree.chart.ChartFactory;
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.NumberAxis;
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.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.DefaultXYZDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
import java.util.Map;
public class JfreeChartUtils {
// 参考文章 https://www.jianshu.com/p/6c4f3832c396
public static String imagePath = "D://123//jfree";
public static void main(String[] args) throws Exception {
// 生成饼图
testPie();
// 生成折线图
testLine();
// 生成柱状图
testBar();
// 生成折线图 多条
testCreateManyLineChart();
// 生成3D柱状图
bar3D();
// 生成气泡图
bubble();
// 生成时序图
sequenceDiagram();
}
public static void testPie(){
//如 果不使用Font,中文将显示不出来
Font font = new Font("新宋体", Font.BOLD, 15);
// 创建数据:饼状图就是名称和值(比例)
Map map=new HashMap();
map.put("录播主机", (double) 1000);
map.put("编码器", (double) 700);
map.put("摄像机", (double) 600);
map.put("流转码服务器", (double) 400);
map.put("腾讯服务器", (double) 150);
// 创建JFreeChart
JFreeChart chart = createPieChart("故障设备类型比例", map, font);
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_饼图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testLine(){
//如 果不使用Font,中文将显示不出来
Font font = new Font("新宋体", Font.BOLD, 15);
// 创建数据
Map> datas =new HashMap>();
Map map1=new HashMap();
Map map2=new HashMap();
Map map3=new HashMap();
Map map4=new HashMap();
Map map5=new HashMap();
Map map6=new HashMap();
Map map7=new HashMap();
Map map8=new HashMap();
map1.put("故障数量", (double) 20);
map2.put("故障数量", (double) 30);
map3.put("故障数量", (double) 25);
map4.put("故障数量", (double) 50);
map5.put("故障数量", (double) 40);
map6.put("故障数量", (double) 25);
map7.put("故障数量", (double) 50);
map8.put("故障数量", (double) 40);
//压入数据
datas.put("一月", map1);
datas.put("二月", map2);
datas.put("三月", map3);
datas.put("四月", map4);
datas.put("五月", map5);
datas.put("六月", map6);
datas.put("七月", map7);
datas.put("八月", map8);
JFreeChart chart = createLineChart("故障数量-时间曲线", datas, "月份", "故障次数(次)", font);
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_折线图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testBar(){
//如 果不使用Font,中文将显示不出来
Font font = new Font("新宋体", Font.BOLD, 15);
// 创建数据
Map> datas =new HashMap>();
Map map1=new HashMap();
Map map2=new HashMap();
Map map3=new HashMap();
map1.put("故障数", (double) 1000);
map2.put("故障数", (double) 1300);
map3.put("故障数", (double) 1000);
//压入数据
datas.put("设备网络掉线", map1);
datas.put("CPU利用率高", map2);
datas.put("磁盘占用高", map3);
datas.put("掉线频率", map3);
datas.put("内存使用率", map2);
datas.put("访问量", map1);
JFreeChart chart = createBarChart("故障类型比例",datas,"故障类型","数量单位(个)",font);
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_柱状图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testCreateManyLineChart(){
String[] title = {"成功量","失败量","异常"};
String[] xValue = {"2021-01","2021-02","2021-03","2021-04","2021-05"};
// 绘图数据集
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
Random r = new Random();
for (int i =0;i> param) {
TreeMap> paramTreeMap = new TreeMap<>(param);
System.out.println(paramTreeMap);
}
public static JFreeChart createPieChart(String title, Map data, Font font) {
try {
Set> set = data.entrySet();
DefaultPieDataset pds = new DefaultPieDataset();
Iterator iterator = set.iterator();
Map.Entry entry;
while (iterator.hasNext()) {
entry = (Map.Entry) iterator.next();
pds.setValue(entry.getKey().toString(), Double.parseDouble(entry.getValue().toString()));
}
// 生成一个饼图的图表:显示图表的标题、组装的数据、是否显示图例、是否生成贴士以及是否生成URL链接
JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, true);
// 设置图片标题的字体
chart.getTitle().setFont(font);
// 得到图块,准备设置标签的字体
PiePlot plot = (PiePlot) chart.getPlot();
//设置分裂效果,需要指定分裂出去的key
// plot.setExplodePercent("摄像机", 0.1); 分裂效果,可选
// 设置标签字体
plot.setLabelFont(font);
// 设置图例项目字体
chart.getLegend().setItemFont(font);
// 设置开始角度
// plot.setStartAngle(new Float(3.14f / 2f)); 开始角度,意义不大
//设置plot的前景色透明度
plot.setForegroundAlpha(0.7f);
//设置plot的背景色透明度
plot.setBackgroundAlpha(0.0f);
//设置标签生成器(默认{0})
//{0}:key {1}:value {2}:百分比 {3}:sum
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}")); // 一般在{1}后面加单位,如:{0}({1}次)/{2}
//将内存中的图片写到本地硬盘
// ChartUtilities.saveChartAsJPEG(new File("H:/a.png"), chart, 600, 300);
return chart;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static JFreeChart createLineChart(String title, Map> data, String type, String unit, Font font) {
try {
DefaultCategoryDataset ds = new DefaultCategoryDataset();
Set>> set1 = data.entrySet();
Iterator iterator1 = set1.iterator();
Iterator iterator2;
HashMap map;
Set> set2;
Map.Entry entry1;
Map.Entry entry2;
while (iterator1.hasNext()) {
entry1 = (Map.Entry) iterator1.next();
map = (HashMap) entry1.getValue();
set2 = map.entrySet();
iterator2 = set2.iterator();
while (iterator2.hasNext()) {
entry2 = (Map.Entry) iterator2.next();
ds.setValue(Double.parseDouble(entry2.getValue().toString()), entry2.getKey().toString(), entry1.getKey().toString());
}
}
//创建折线图,折线图分水平显示和垂直显示两种
// //2D折线图
JFreeChart chart = ChartFactory.createLineChart(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, true);
// //3D折线图
JFreeChart chart2 = ChartFactory.createLineChart3D(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, false);
//设置整个图片的标题字体
chart.getTitle().setFont(font);
//设置提示条字体
font = new Font("宋体", Font.BOLD, 15);
chart.getLegend().setItemFont(font);
//得到绘图区
CategoryPlot plot = (CategoryPlot) chart.getPlot();
//得到绘图区的域轴(横轴),设置标签的字体
plot.getDomainAxis().setLabelFont(font);
// 设置背景透明度
plot.setBackgroundAlpha(0.1f);
// 设置网格横线颜色
plot.setRangeGridlinePaint(Color.gray);
// 设置网格横线大小
plot.setDomainGridlineStroke(new BasicStroke(0.2F));
plot.setRangeGridlineStroke(new BasicStroke(0.2F));
//设置横轴标签项字体
plot.getDomainAxis().setTickLabelFont(font);
// 生成折线图上的数字
//绘图区域(红色矩形框的部分)
LineAndShapeRenderer lineAndShapeRenderer=(LineAndShapeRenderer)plot.getRenderer();
lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
//设置图表上的数字可见
lineAndShapeRenderer.setBaseItemLabelsVisible(true);
//设置图表上的数字字体
lineAndShapeRenderer.setBaseItemLabelFont(new Font("宋体",Font.BOLD,15));
//设置折线图拐角上的正方形
//创建一个正方形
Rectangle shape=new Rectangle(4,4);
lineAndShapeRenderer.setSeriesShape(0, shape);
//设置拐角上图形可见
lineAndShapeRenderer.setSeriesShapesVisible(0, true);
//设置范围轴(纵轴)字体
font = new Font("宋体", Font.BOLD, 18);
plot.getRangeAxis().setLabelFont(font);
// plot.setForegroundAlpha(1.0f);
return chart;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static JFreeChart createManyLineChart(DefaultCategoryDataset dataSet){
//如果把createLineChart改为createLineChart3D就变为了3D效果的折线图
JFreeChart chart = ChartFactory.createLineChart("图表标题", "X轴标题", "Y轴标题", dataSet,
PlotOrientation.VERTICAL, // 绘制方向
true, // 显示图例
true, // 采用标准生成器
false // 是否生成超链接
);
//如 果不使用Font,中文将显示不出来
Font font = new Font("新宋体", Font.BOLD, 15);
chart.getTitle().setFont(font); // 设置标题字体
chart.getLegend().setItemFont(font);// 设置图例类别字体
// chart.setBackgroundPaint();// 设置背景色
//获取绘图区对象
CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.LIGHT_GRAY); // 设置绘图区背景色
plot.setRangeGridlinePaint(Color.gray); // 设置水平方向背景线颜色
// 设置背景透明度
plot.setBackgroundAlpha(0.1f);
// 设置网格横线颜色
plot.setRangeGridlinePaint(Color.gray);
// 设置网格横线大小
plot.setDomainGridlineStroke(new BasicStroke(0.2F));
plot.setRangeGridlineStroke(new BasicStroke(0.2F));
plot.setRangeGridlinesVisible(true);// 设置是否显示水平方向背景线,默认值为true
plot.setDomainGridlinePaint(Color.WHITE); // 设置垂直方向背景线颜色
plot.setDomainGridlinesVisible(true); // 设置是否显示垂直方向背景线,默认值为false
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(font); // 设置横轴字体
domainAxis.setTickLabelFont(font);// 设置坐标轴标尺值字体
domainAxis.setLowerMargin(0.01);// 左边距 边框距离
domainAxis.setUpperMargin(0.06);// 右边距 边框距离,防止最后边的一个数据靠近了坐标轴。
domainAxis.setMaximumCategoryLabelLines(2);
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(font);
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);
for (int i = 0; i < dataSet.getRowCount(); i++) {
if (i % 2 == 0) {
renderer.setSeriesStroke(i, realLine); // 利用实线绘制
} else {
renderer.setSeriesStroke(i, brokenLine); // 利用虚线绘制
}
// 生成折线图上的数字
//绘图区域(红色矩形框的部分)
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
//设置图表上的数字可见
renderer.setBaseItemLabelsVisible(true);
//设置图表上的数字字体
renderer.setBaseItemLabelFont(new Font("宋体",Font.BOLD,15));
//设置折线图拐角上的正方形
//创建一个正方形
Rectangle shape=new Rectangle(4,4);
renderer.setSeriesShape(0, shape);
//设置拐角上图形可见
renderer.setSeriesShapesVisible(0, true);
}
plot.setNoDataMessage("无对应的数据,请重新查询。");
plot.setNoDataMessageFont(font);//字体的大小
plot.setNoDataMessagePaint(Color.RED);//字体颜色
return chart;
}
public static JFreeChart createBarChart(String title,Map> data,String type,String danwei,Font font){
try {
//种类数据集
DefaultCategoryDataset ds = new DefaultCategoryDataset();
//获取迭代器:
Set>> set1 = data.entrySet();
Iterator iterator1= set1.iterator();
Iterator iterator2;
HashMap map;
Set> set2;
Map.Entry entry1;
Map.Entry entry2;
while(iterator1.hasNext()){
entry1=(Map.Entry) iterator1.next();
map=(HashMap) entry1.getValue();
set2=map.entrySet();
iterator2=set2.iterator();
while (iterator2.hasNext()) {
entry2= (Map.Entry) iterator2.next();
ds.setValue(Double.parseDouble(entry2.getValue().toString()), entry2.getKey().toString(), entry1.getKey().toString());
}
}
//创建柱状图,柱状图分水平显示和垂直显示两种
JFreeChart chart = ChartFactory.createBarChart(title, type, danwei, ds, PlotOrientation.VERTICAL, true, true, true);
//设置整个图片的标题字体
chart.getTitle().setFont(font);
//设置提示条字体
font = new Font("宋体", Font.BOLD, 15);
chart.getLegend().setItemFont(font);
//得到绘图区
CategoryPlot plot = (CategoryPlot) chart.getPlot();
//得到绘图区的域轴(横轴),设置标签的字体
plot.getDomainAxis().setLabelFont(font);
//获取X轴的对象
// CategoryAxis categoryAxis = plot.getDomainAxis();
// 设置X轴文本倾斜45度
// categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
// 设置背景透明度
plot.setBackgroundAlpha(0.1f);
// 设置网格横线颜色
plot.setRangeGridlinePaint(Color.gray);
// 设置网格横线大小
plot.setDomainGridlineStroke(new BasicStroke(0.2F));
plot.setRangeGridlineStroke(new BasicStroke(0.2F));
//设置横轴标签项字体
plot.getDomainAxis().setTickLabelFont(font);
// 设置柱状图柱子相关
CategoryPlot categoryPlot = chart.getCategoryPlot();
BarRenderer rendererBar = (BarRenderer) categoryPlot.getRenderer();
// 柱子宽度
rendererBar.setMaximumBarWidth(0.05);
// 柱状图颜色
rendererBar.setSeriesPaint(0, Color.decode("#005AB5"));
//设置范围轴(纵轴)字体
plot.getRangeAxis().setLabelFont(font);
plot.setForegroundAlpha(1.0f);
return chart;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void bar3D() {
final String fait = "菲亚特";
final String audi = "奥迪";
final String ford = "福特";
final String speed = "速度";
final String popular = "喜欢程度";
final String mailage = "邮寄";
final String userrating = "用户评价";
final String safty = "安全性";
final DefaultCategoryDataset dataset = new DefaultCategoryDataset( );
dataset.addValue( 1.0 , fait , speed );
dataset.addValue( 4.0 , fait , popular );
dataset.addValue( 3.0 , fait , userrating );
dataset.addValue( 5.0 , fait , mailage );
dataset.addValue( 5.0 , fait , safty );
dataset.addValue( 5.0 , audi , speed );
dataset.addValue( 7.0 , audi , popular );
dataset.addValue( 6.0 , audi , userrating );
dataset.addValue( 10.0 , audi , mailage );
dataset.addValue( 4.0 , audi , safty );
dataset.addValue( 4.0 , ford , speed );
dataset.addValue( 3.0 , ford , popular );
dataset.addValue( 2.0 , ford , userrating );
dataset.addValue( 3.0 , ford , mailage );
dataset.addValue( 6.0 , ford , safty );
// 设置字体,去除中文乱码
StandardChartTheme sct = new StandardChartTheme("CN");
sct.setExtraLargeFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));
sct.setRegularFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));
sct.setLargeFont(new Font("宋体", Font.LAYOUT_LEFT_TO_RIGHT, 15));
ChartFactory.setChartTheme(sct);
JFreeChart chart = ChartFactory.createBarChart3D(
"汽车使用统计",
"类别",
"值",
dataset,
PlotOrientation.VERTICAL,
true, true, false);
// 注释的代码放开就是背景透明
int width = 640;
int height = 480;
// 标注位于上侧
chart.getLegend().setPosition(RectangleEdge.TOP);
// 设置标注无边框
chart.getLegend().setFrame(new BlockBorder(Color.WHITE));
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_3D柱状图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void bubble() {
DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset( );
double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 };
double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 };
double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 };
double ad3[ ][ ] = { ad , ad1 , ad2 };
defaultxyzdataset.addSeries( "系统1" , ad3 );
JFreeChart jfreechart = ChartFactory.createBubbleChart(
"年龄、体重和工作",
"重量",
"年龄",
defaultxyzdataset,
PlotOrientation.HORIZONTAL,
true, true, false);
XYPlot xyplot = ( XYPlot )jfreechart.getPlot();
xyplot.setForegroundAlpha( 0.65F );
XYItemRenderer xyitemrenderer = xyplot.getRenderer( );
xyitemrenderer.setSeriesPaint( 0 , Color.blue );
NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( );
numberaxis.setLowerMargin( 0.2 );
numberaxis.setUpperMargin( 0.5 );
NumberAxis numberAxis = ( NumberAxis )xyplot.getRangeAxis( );
numberAxis.setLowerMargin( 0.8 );
numberAxis.setUpperMargin( 0.9 );
// 注释的代码是设置背景透明度
int width = 560;
int height = 370;
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_气泡图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, jfreechart, width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sequenceDiagram(){
final TimeSeries series = new TimeSeries( "Random Data" );
Second current = new Second();
double value = 100.0;
for ( int i = 0 ; i < 4000 ; i++ )
{
try {
value = value + Math.random( ) - 0.5;
series.add( current , new Double( value ) );
current = ( Second ) current.next( );
} catch ( SeriesException e ) {
System.err.println( "Error adding to series" );
}
}
final XYDataset dataset=( XYDataset )new TimeSeriesCollection(series);
JFreeChart timeChart = ChartFactory.createTimeSeriesChart(
"计算测试",
"秒数",
"值",
dataset,
false,
false,
false);
// 注释的代码是设置背景透明度
int width = 560;
int height = 370;
//在D盘目录下生成图片
File p = new File(imagePath);
if (!p.exists()) {
p.mkdirs();
}
String imageName = System.currentTimeMillis() + "_时序图" + ".jpeg";
File file = new File(p.getPath() + "/" + imageName);
try {
if(file.exists()) {
file.delete();
}
ChartUtilities.saveChartAsJPEG(file, timeChart, width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
}



