一.步骤:
- 创建数据集(准备数据)
- 根据数据集生成JFreeChart对象,并对其做相应的设置(标题,图例,x轴,Y轴,对象渲染等)
- 将JFreeChart对象输出到文件或者Servlet输出流等
二.具体举例
饼状图
示例代码:
package com.lky.experiment; import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
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.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset; /**
* @Title: allProductDistribution.java
* @Package com.lky.experiment
* @Description: 产品评论量分布
* @author lky
* @date 2015年11月18日 下午3:50:36
* @version V1.0
*/
public class allProductDistribution { public void PieChart(String path) {
PieDataset dataset = getDataSet(); JFreeChart chart = ChartFactory.createPieChart3D("产品评论量分布图", dataset, true, true, false);
chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));// 设置图例字体样式
chart.getTitle().setFont(new Font("黑体", Font.CENTER_BASELINE, 20));// 设置标题字体样式
chart.setBackgroundPaint(Color.white);// 设置背景色为白色 PiePlot3D plot = (PiePlot3D) chart.getPlot();// 图样式(饼状图)
plot.setLabelFont(new Font("宋体", Font.PLAIN, 14));// 图中标签字体样式 // 图片中显示百分比:默认方式
// plot.setLabelGenerator(new
// StandardPieSectionLabelGenerator(StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
// 自定义图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{1}({2})", NumberFormat.getNumberInstance(), new DecimalFormat("0.000%"))); // 自定义图例中显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{1}({2})")); // 指定图片的透明度(0.0-1.0)
plot.setForegroundAlpha(1.0f);
// 指定显示的饼图上圆形(false)还椭圆形(true)
plot.setCircular(true);
plot.setBackgroundAlpha(0.5f);// 背景色 透明度
plot.setBackgroundPaint(new Color(255, 255, 204));// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确) try {
File file = new File(path);
ChartUtilities.saveChartAsPNG(file, chart, 640, 480);// 把生成的图保存到文件中
} catch (Exception e) {
e.printStackTrace();
}
ChartPreview(chart);// 显示生成的图
} /**
*
* @Title getDataSet
* @Description 获取饼图数据
*
*/
private PieDataset getDataSet() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("0-300(条)", new Double(65));
dataset.setValue("300-600(条)", new Double(4));
dataset.setValue("600-900(条)", new Double(3));
dataset.setValue("1200-1500(条)", new Double(2));
dataset.setValue("2700-3000(条)", new Double(1));
dataset.setValue("3000+(条)", new Double(17));
dataset.setValue("0(条)", new Double(19));
return dataset;
} /**
* @Title ChartPreview
* @Description 预览图片
*
*/
private void ChartPreview(JFreeChart chart) {
// ******************************//
// * 将生成的报表放到预览窗口中
// ******************************//
final ChartFrame preview = new ChartFrame("评论统计信息", chart);
preview.addWindowListener(new WindowAdapter() {
public void windowClosing(final WindowEvent event) {
preview.dispose();
}
});
preview.pack(); // 调整预览窗口的大小和位置,适合屏幕,并且居中
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
preview.setSize(screenSize.width, screenSize.height - 50);// 适合屏幕,50表示把工具栏要考虑在内
Dimension frameSize = preview.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
preview.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height - 50) / 2);
preview.setVisible(true);// 显示报表预览窗口
} public static void main(String args[]) {
new allProductDistribution().PieChart("pie.png");
}
}
柱状图
示例代码:
package com.lky.experiment; import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList; 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.ValueAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset; import com.lky.spider.pojos.dateData; /**
* @Title: allProductMouthStatistics.java
* @Package com.lky.experiment
* @Description: 商城手机月统计量
* @author lky
* @date 2015年11月18日 下午4:09:57
* @version V1.0
*/
public class allProductMouthStatistics { public void mouthBarChart(String year, String path) {
CategoryDataset dataset = getMouthCateDataSet(year);
JFreeChart chart = ChartFactory.createBarChart3D(year+"年商城手机产品评论量", // 图表标题
"月份", // 目录轴的显示标签
"评论总数", // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向:水平、垂直
true, // 是否显示图例(对于简单的柱状图必须是false)
true, // 是否生成工具
true // 是否生成URL链接
); chart.getTitle().setFont(new Font("黑体", Font.CENTER_BASELINE, 20));// 设置图标题的字体
chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));// 设置图例字体
chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); CategoryPlot plot = chart.getCategoryPlot();// 获得图表区域对象
plot.setRangeGridlinesVisible(true); // 设置横虚线可见
plot.setRangeGridlinePaint(Color.gray); // 虚线色彩
plot.setForegroundAlpha(1.0f);// 设置柱的透明度
plot.setBackgroundAlpha(0.5f);// 背景色 透明度
plot.setBackgroundPaint(new Color(255, 255, 204));// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确) /** X 轴 设置 **/
Font xfont = new Font("宋体", Font.PLAIN, 12);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLowerMargin(0.1);// 设置距离图片左端距离此时为10%
domainAxis.setUpperMargin(0.1);// 设置距离图片右端距离此时为百分之10
domainAxis.setCategoryLabelPositionOffset(10);// 图表横轴与标签的距离(10像素)
domainAxis.setCategoryMargin(0.2);// 横轴标签之间的距离20% domainAxis.setLabelFont(xfont);// X轴标题
domainAxis.setLabelPaint(Color.red);// 标题的颜色
domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));// X轴数值
domainAxis.setTickLabelPaint(Color.BLUE); // X轴数值的字体颜色
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD); // 横轴上的label斜显示
plot.setDomainAxis(domainAxis);
/** X 轴 **/ /** Y 轴 设置 **/
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setUpperMargin(0.1);// 设置最高的一个柱与图片顶端的距离(最高柱的10%)
rangeAxis.setLabelFont(xfont);// Y轴标题
rangeAxis.setLabelPaint(Color.red);// Y轴标题的颜色
rangeAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));// Y轴数值
plot.setRangeAxis(rangeAxis);
/** Y 轴 设置 **/ /** 使用自定义的渲染器 **/
CustomRenderer renderer = new CustomRenderer();
renderer.setMaximumBarWidth(0.6);// 设置柱子宽度
renderer.setMinimumBarLength(0.2);// 设置柱子高度
renderer.setBaseOutlinePaint(Color.BLACK);// 设置柱子边框颜色
renderer.setDrawBarOutline(true);// 设置柱子边框可见
renderer.setItemMargin(0.2);// 设置每个地区所包含的平行柱的之间距离 // 显示每个柱的数值,并修改该数值的字体属性
renderer.setIncludeBaseInRange(true);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
plot.setRenderer(renderer);// 设置使用的渲染
/** 使用自定义的渲染器 **/ try {
File file = new File(path);
ChartUtilities.saveChartAsPNG(file, chart, 400, 300);// 把报表保存为文件
} catch (Exception e) {
String s = e.getLocalizedMessage();
s = e.getMessage();
System.out.println(s);
} ChartPreview(chart);
} private CategoryDataset getMouthCateDataSet(String year) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
ArrayList<dateData> result = statistics.allMouthStatistics(year); for (dateData ss : result) {
Integer count = ss.getCount();
String ym = ss.getSdate(); if (ym.substring(5, 7).equals("11")) {
continue;
}
dataset.addValue(count, ym, ym);
// System.out.println(count + "-------->" + ym);
}
return dataset;
} /**
* @Title ChartPreview
* @Description 预览图片
*
*/
private void ChartPreview(JFreeChart chart) {
// ******************************//
// * 将生成的报表放到预览窗口中
// ******************************//
final ChartFrame preview = new ChartFrame("评论统计信息", chart);
preview.addWindowListener(new WindowAdapter() {
public void windowClosing(final WindowEvent event) {
preview.dispose();
}
});
preview.pack(); // 调整预览窗口的大小和位置,适合屏幕,并且居中
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
preview.setSize(screenSize.width, screenSize.height - 50);// 适合屏幕,50表示把工具栏要考虑在内
Dimension frameSize = preview.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
preview.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height - 50) / 2);
preview.setVisible(true);// 显示报表预览窗口
} public static void main(String args[]) {
new allProductMouthStatistics().mouthBarChart("2015", "2015.png");
} }
折线图
示例代码:
package com.lky.experiment; import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList; 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.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYSplineRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection; import com.lky.spider.pojos.dateData; public class hourShow { /**
* @Title ChartPreview
* @Description 预览图片
*
*/
private void ChartPreview(JFreeChart chart) {
// ******************************//
// * 将生成的报表放到预览窗口中
// ******************************//
final ChartFrame preview = new ChartFrame("评论量", chart);
preview.addWindowListener(new WindowAdapter() {
public void windowClosing(final WindowEvent event) {
preview.dispose();
}
});
preview.pack(); // 调整预览窗口的大小和位置,适合屏幕,并且居中
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
preview.setSize(screenSize.width, screenSize.height - 50);// 适合屏幕,50表示把工具栏要考虑在内
Dimension frameSize = preview.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
preview.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height - 50) / 2); // 显示报表预览窗口 preview.setVisible(true);
} /**
* @Title: XYSplineRendererGo
* @Description: 获取一段时间内一定时间粒度商城手机产品的评论量
* @param tstart 起始时间
* @param tend 结束时间
* @param size 时间粒度
* @param path 图片路径
*/
public void XYSplineRendererHour(String tstart, String tend, int size, String path) {
XYDataset dataset = getXYDataset(tstart, tend, size); JFreeChart chart = ChartFactory.createXYLineChart("("+tstart+":"+tend+")商城手机产品评论量", "小时", "评论量", dataset, PlotOrientation.VERTICAL, true, false, false);
chart.getTitle().setFont(new Font("黑体", Font.CENTER_BASELINE, 20));// 设置图标题的字体
chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));// 设置图例字体 XYPlot plot = (XYPlot) chart.getPlot();
plot.setRangeGridlinesVisible(true); // 设置横虚线可见
plot.setRangeGridlinePaint(Color.gray); // 虚线色彩
plot.setForegroundAlpha(1.0f);// 设置柱的透明度
plot.setBackgroundAlpha(0.5f);// 背景色 透明度
plot.setBackgroundPaint(new Color(255, 255, 204));// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确) Font xfont = new Font("宋体", Font.PLAIN, 12);
ValueAxis domainAxis = plot.getDomainAxis();
domainAxis.setLowerMargin(0.1);// 设置距离图片左端距离此时为10%
domainAxis.setUpperMargin(0.1);// 设置距离图片右端距离此时为百分之10
domainAxis.setLabelFont(xfont);// X轴标题
domainAxis.setLabelPaint(Color.green);// X轴标题颜色
domainAxis.setTickLabelFont(xfont);// X轴数值字体
domainAxis.setTickLabelPaint(Color.BLUE); // X轴数值颜色 NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setUpperMargin(0.1);// 设置最高的一个柱与图片顶端的距离(最高柱的10%)
rangeAxis.setLabelFont(xfont);// Y轴标题
rangeAxis.setLabelPaint(Color.green); // Y轴标题颜色
rangeAxis.setTickLabelFont(xfont);// Y轴数值字体
rangeAxis.setTickLabelPaint(Color.BLUE);// Y轴数值颜色 // NumberFormat numberformat = new DecimalFormat("00%");
// rangeAxis.setNumberFormatOverride(numberformat);// 设置y轴以百分比方式显示 // 平滑曲线
XYItemRenderer renderer = new XYSplineRenderer();
renderer.setBaseItemLabelPaint(Color.black);// 字体为黑色
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelFont(new Font("宋体", Font.PLAIN, 12));
plot.setRenderer(renderer); try {
File file = new File(path);
ChartUtilities.saveChartAsPNG(file, chart, 400, 300);// 把报表保存为文件
} catch (Exception e) {
String s = e.getLocalizedMessage();
s = e.getMessage();
System.out.println(s);
}
ChartPreview(chart);
} private XYSeriesCollection getXYDataset(String tstart, String tend, int size) {
XYSeries dataSeries = new XYSeries("粒度"+size+"(h)"); ArrayList<dateData> result = statistics.allHourStatistics(tstart, tend);
// for (dateData ss : result) {
// System.out.println(ss.getSdate());
// }
int[] _count = new int[20000];
int index = -1;
for (dateData ss : result) {
_count[(++index) / size] += ss.getCount();
} for (int i = 0; i <= index / size; ++i) {
dataSeries.add(i + 1, _count[i]);
}
XYSeriesCollection xyDataset = new XYSeriesCollection();
xyDataset.addSeries(dataSeries);
return xyDataset;
} public static void main(String args[]){
// new hourShow().XYSplineRendererGo("2015-11-5","2015-11-6",2, "xy.png");
new hourShow().XYSplineRendererHour("2014-11-5","2014-11-6",2, "xy1.png");
}
}
时间序列图
示例代码:
package com.lky.experiment; import java.awt.Font;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset; import com.lky.spider.pojos.dateData;
import com.lky.spider.utils.TimeUtil; @SuppressWarnings("deprecation")
public class dayShow {
private ChartPanel frame1;
private String sid; public dayShow(String sid ,String title) {
this.sid=sid;
XYDataset xydataset = createDataset();//数据集 JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title+"---日统计图", "日期", "数量", xydataset, true, true, true);
XYPlot xyplot = (XYPlot) jfreechart.getPlot(); DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
dateaxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM"));
dateaxis.setLabelFont(new Font("黑体", Font.BOLD, 14)); // 水平底部标题
dateaxis.setTickLabelFont(new Font("宋体", Font.BOLD, 12)); // 垂直标题 ValueAxis rangeAxis = xyplot.getRangeAxis();// 获取y轴
rangeAxis.setLabelFont(new Font("黑体", Font.BOLD, 15)); jfreechart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
jfreechart.getTitle().setFont(new Font("宋体", Font.BOLD, 15));// 设置标题字体 frame1 = new ChartPanel(jfreechart, true);
} private XYDataset createDataset() { // 这个数据集有点多,但都不难理解
ArrayList<String> cleanList = statistics.cleanData(sid);
TimeSeries timeseries1 = new TimeSeries("每天的评论数量", org.jfree.data.time.Day.class);
ArrayList<dateData> info = statistics.getDayStatistics(cleanList); timeseries1.add(new Day(TimeUtil.ymdTDate(info.get(0).getSdate())), info.get(0).getCount());
String nextday = TimeUtil.nextDay(info.get(0).getSdate());
for (int i = 1; i < info.size();) {
if (nextday.equals(info.get(i).getSdate())) { // 过滤评论数大于500的
if (info.get(i).getCount() > 500) {
i++;
continue;
}
timeseries1.add(new Day(TimeUtil.ymdTDate(nextday)), info.get(i).getCount());
i++;
} else {
timeseries1.add(new Day(TimeUtil.ymdTDate(nextday)), 0);
}
nextday = TimeUtil.nextDay(nextday);
} TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
timeseriescollection.addSeries(timeseries1);
return timeseriescollection;
} public ChartPanel getChartPanel() {
return frame1;
}
}
//获取某一个商品的日次评论量
public static void getDayShow(String sid,String title){
JFrame frame = new JFrame("日统计图");
frame.setLayout(new GridLayout(2, 2, 10, 10)); frame.add(new dayShow(sid,title).getChartPanel()); // 添加折线图
frame.setBounds(50, 50, 800, 600);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}