简介
JFreeChart是一个免费创建图片的java工具. 目前是最好的 java 图形解决方案
JFreeChart是开放源代码站点SourceForge.net上的一个JAVA项目,它主要用来各种各样的图表,这些图表包括:饼图、柱状图(普通柱状图以及堆栈柱状图)、线图、区域图、分布图、混合图、甘特图以及一些仪表盘等等。这些不同式样的图表基本上可以满足目前的要求。
使用
准备jar包
- jcommon-1.0.12.jar
- jfreechart-1.0.8a.jar
下载jar包的地方
线型图
/**
* 生成折线图
*/
public static String getCreateWireChart(){
double[][] data = new double[][]{{ 1222,333,4444.4,555.3,6.23,7.23,2,8,3,0 }};
String[] rowKeys ={"登入用户数"};
String[] columnKeys = {"2021/02/24","2021/02/23","2021/02/22","2021/02/21","2021/02/20","2021/02/19","2021/02/18","2021/02/17","2021/02/16","2021/02/15",};
CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
return createWireChar("登入用户数趋势", "", "", dataset, "wire.png");
}
// 折线图 数据集
public static CategoryDataset getBarData(double[][] data, String[] rowKeys,String[] columnKeys){
return DatasetUtilities
.createCategoryDataset(rowKeys, columnKeys, data);
}
/**
* 折线图
*
* @param chartTitle
* @param x
* @param y
* @param xyDataset
* @param charName
* @return
*/
public static String createWireChar(String chartTitle, String x, String y,
CategoryDataset xyDataset, String charName){
JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y,
xyDataset, PlotOrientation.VERTICAL, true, true, false);
chart.setTextAntiAlias(false);
chart.setBackgroundPaint(Color.WHITE);
chart.setBorderVisible(false); //设置边框是否可见
CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
// 设置面板字体
Font labelFont = new Font("宋体", Font.TRUETYPE_FONT, 12);
CategoryAxis domainAxis = categoryplot.getDomainAxis();
domainAxis.setLabelFont(labelFont);// 轴标题
domainAxis.setTickLabelFont(labelFont);// 轴数值
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45); // 横轴上的
NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
numberaxis.setAutoRangeIncludesZero(true);
// 设置图标题的字体重新设置title
Font font = new Font("隶书", Font.BOLD, 25);
TextTitle title = new TextTitle(chartTitle);
title.setFont(font);
chart.setTitle(title);
ValueAxis valueAxis = categoryplot.getRangeAxis();
valueAxis.setAutoRange(true); //是否自动设置数据轴数据范围
valueAxis.setVisible(false);
// 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!
LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();
lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见
lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见
lineandshaperenderer.setBaseItemLabelsVisible(true);
lineandshaperenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}%",NumberFormat.getNumberInstance()));
FileOutputStream fos_jpg = null;
try
{
isChartPathExist(CeShiUtil.CHART_PATH);
String chartName = CeShiUtil.CHART_PATH + charName;
fos_jpg = new FileOutputStream(chartName);
// 将报表保存为png文件
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 1000, 400);
return chartName;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally
{
try
{
fos_jpg.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
* 判断文件夹是否存在,如果不存在则新建
* @param chartPath
*/
private static void isChartPathExist(String chartPath){
File file = new File(chartPath);
if (!file.exists())
{
file.mkdirs();
}
}
}
柱状图
/**
* 生成柱状图
* @return
*/
public static String getCreatePillarChart(){
double[][] data = new double[][]{
{120,22,22,425,6,82,122,524,76,325,324,10}
};
String[] rowKeys = { "" };
String[] columnKeys = { "2021/01","2021/02","2021/03","2021/04","2021/05","2021/06","2021/07","2021/08","2021/09","2021/10","2021/11","2021/12", };
CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
return createBarChart(null,dataset, "", "", "月用户存留率", "pillar.png");
}
//柱状图 数据集
public static CategoryDataset getBarData(double[][] data, String[] rowKeys,String[] columnKeys){
return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);
}
/**
* 柱状图
*
*@param dataset 数据集
* @param xName x轴的说明(如种类,时间等)
* @param yName y轴的说明(如速度,时间等)
* @param chartTitle 图标题
* @param charName 生成图片的名字
* @return
*/
public static String createBarChart(String type,CategoryDataset dataset, String xName,String yName, String chartTitle, String charName){
JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题
xName,
yName,
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);
// 数据轴精度
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);// 轴数值
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 是否完整显示
// 设置距离图片左端距离
domainAxis.setLowerMargin(0.1);
// 设置距离图片右端距离
domainAxis.setUpperMargin(0.1);
plot.setDomainAxis(domainAxis);
// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)
plot.setBackgroundPaint(new Color(255, 255, 204));
// y轴设置
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(labelFont);
rangeAxis.setTickLabelFont(labelFont);
// 设置最高的一个 Item 与图片顶端的距离
rangeAxis.setUpperMargin(0.15);
// 设置最低的一个 Item 与图片底端的距离
rangeAxis.setLowerMargin(0.15);
plot.setRangeAxis(rangeAxis);
BarRenderer renderer = new BarRenderer();
// 设置柱子宽度
renderer.setMaximumBarWidth(0.03);
// 设置柱子高度
renderer.setMinimumBarLength(0.2);
// 设置柱子边框颜色
renderer.setBaseOutlinePaint(Color.BLACK);
// 设置柱子边框可见
renderer.setDrawBarOutline(true);
renderer.setIncludeBaseInRange(true);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
renderer.setAutoPopulateSeriesFillPaint(true);//自动填充柱状体颜色
renderer.setItemMargin(0.3);
plot.setRenderer(renderer);
// 设置柱的透明度
plot.setForegroundAlpha(1.0f);
FileOutputStream fos_jpg = null;
try
{
isChartPathExist(CeShiUtil.CHART_PATH);
String chartName = CeShiUtil.CHART_PATH + charName;
fos_jpg = new FileOutputStream(chartName);
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 800, 500, true, 10);
return chartName;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally
{
try
{
fos_jpg.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
* 判断文件夹是否存在,如果不存在则新建
* @param chartPath
*/
private static void isChartPathExist(String chartPath){
File file = new File(chartPath);
if (!file.exists()) {
file.mkdirs();
}
}
环形图
/**
* 生成环形图
* @return
*/
public static String getCreateAnnularChart(){
String[] keys = { "光伏用户", "能源用户","光伏+储能","自发自用用户","离网储能" };
double[] data = { 308,308,200,13,308 };
String img_title = "用户登入统计";
String img_name = "pei.png";
PieDataset pset = getAnnularData(data, keys);
return createAnnularChar(pset, img_title,img_name, keys);
}
// 环形图 数据集
public static PieDataset getAnnularData(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 void main(String[] args) {
}
/**
* 环形图
*
* @param dataset 数据集
* @param chartTitle 图标题
* @param charName 生成图的名字
* @param pieKeys 分饼的名字集
* @return
*/
public static String createAnnularChar(PieDataset dataset,
String chartTitle, String charName, String[] pieKeys){
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, 14));
// 设置饼状图和环形图的显示数字。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);
Font font2 = new Font("宋体", Font.BOLD, 15);
TextTitle title2 = new TextTitle("累积登入用户:"+854016);
title2.setFont(font2);
chart.addSubtitle(title2);
FileOutputStream fos_jpg = null;
try
{
// 文件夹不存在则创建
isChartPathExist(CeShiUtil.CHART_PATH);
String chartName = CeShiUtil.CHART_PATH + charName;
fos_jpg = new FileOutputStream(chartName);
// 高宽的设置影响椭圆饼图的形状
ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 300);
return chartName;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally
{
try
{
fos_jpg.close();
System.out.println("create pie-chart.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
* 判断文件夹是否存在,如果不存在则新建
* @param chartPath
*/
private static void isChartPathExist(String chartPath){
File file = new File(chartPath);
if (!file.exists())
{
file.mkdirs();
}
}