JFreeChart是JAVA平台上的一个开放的图表绘制类库。它完全使用JAVA语言编写,是为applications, applets, servlets 以及JSP等使用所设计。JFreeChart可生成饼图(pie charts)、柱状图(bar charts)、散点图(scatter plots)、时序图(time series)、甘特图(Gantt charts)等等多种图表,并且可以产生PNG和JPEG格式的输出,还可以与PDF和EXCEL关联。
测试饼状图
创建一个web工程,并在lib中导入对应的JfreeChart所需的jar包
在web.xml中添加servlet
<servlet> <servlet-name>DisplayChart</servlet-name> <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class> </servlet> <servlet-mapping> <servlet-name>DisplayChart</servlet-name> <url-pattern>/DisplayChart</url-pattern> </servlet-mapping> |
创建BarChart01.java用于生成图片,并返回图片名称(DefaultCategoryDataset默认的)
/** * * @ClassName: BarChart01 * @Description: TODO (垂直显示柱状图) * @author A我去 * @date 2019年10月12日下午10:08:51 */ public class BarChart01 { public static String getBarChart(HttpSession session) throws Exception { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(510, "深圳", "苹果"); dataset.addValue(340, "深圳", "香蕉"); dataset.addValue(890, "深圳", "橘子"); dataset.addValue(673, "深圳", "猕猴桃"); dataset.addValue(900, "深圳", "西瓜"); dataset.addValue(560, "深圳", "桃子"); JFreeChart chart = ChartFactory.createBarChart3D ("水果销售情况", "水果", "销售", dataset, PlotOrientation.VERTICAL, true,true,true); String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, null, session); return fileName; } } 注意:PlotOrientation.VERTICAL为垂直排列图表 |
编写页面barchart01.jsp
<% String fileName = BarChart01.getBarChart(session); System.out.println(fileName); %> <img alt="fuck" src="DisplayChart?filename=<%=fileName%>" width="700" height="500"> 注意:filename为固定传入值,不可修改为其他名字 |
启动工程,并输入网址后即可生成图表
垂直图表 |
如果要生成横向图表
public class BarChart02 {
public static String getBarChart(HttpSession session) throws Exception { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(510, "深圳", "苹果"); dataset.addValue(340, "深圳", "香蕉"); dataset.addValue(890, "深圳", "橘子"); dataset.addValue(673, "深圳", "猕猴桃"); dataset.addValue(900, "深圳", "西瓜"); dataset.addValue(560, "深圳", "桃子"); JFreeChart chart = ChartFactory.createBarChart3D("水果销售情况", "水果", "销售", dataset, PlotOrientation.HORIZONTAL, true, true, true); String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, null, session); return fileName; } }
只需将PlotOrientation.HORIZONTAL 水平图表 |
生成图表如下图
|
定制化图表
创建BarChart03.java(使用CategoryDataset定制化按照颜色分类的)
public class BarChart03 {
public static String getBarChart(HttpSession session) throws Exception { double[][] data = { { 1320 }, { 450 }, { 890 }, { 390 } }; String[] rowKeys = { "苹果", "香蕉", "橘子", "梨子" }; String[] columnKeys = { "深圳" }; CategoryDataset dataset = DatasetUtilities.createCategoryDataset (rowKeys, columnKeys, data); JFreeChart chart = ChartFactory.createBarChart3D("水果销售统计图", "水果", "销售", dataset, PlotOrientation.VERTICAL, true, true, true); String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, null, session); return fileName; } } |
创建barchart03.jsp
<% String fileName = BarChart03.getBarChart(session); System.out.println(fileName); %> <img alt="fuck" src="DisplayChart?filename=<%=fileName%>" width="700" height="500"> |
生成图表如下图
|
创建BarChart04.java(多维度统计图)
public class BarChart04 {
public static String getBarChart(HttpSession session) throws Exception { double[][] data = { { 1320, 234, 453, 345 } ,{ 450, 1230, 378, 356 } ,{ 890, 353, 234, 667 } ,{ 390, 231, 553, 453 } }; String[] rowKeys = { "苹果", "香蕉", "橘子", "梨子" }; String[] columnKeys = { "深圳", "上海", "北京", "杭州" }; CategoryDataset dataset = DatasetUtilities .createCategoryDataset(rowKeys, columnKeys, data); JFreeChart chart = ChartFactory.createBarChart3D("水果销售统计图", "水果", "销售", dataset ,PlotOrientation.VERTICAL ,true, true, true); String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, null, session); return fileName; } } |
创建barchart04.jsp
<body> <% String fileName = BarChart04.getBarChart(session); System.out.println(fileName); %> <img alt="fuck" src="DisplayChart?filename=<%=fileName%>" width="700" height="500"> </body> |
生成如下图
|
创建BarChart05.java(多维度统计图,自定义的数值,间距,背景作色)
public class BarChart05 {
public static String getBarChart(HttpSession session) throws Exception { double[][] data = { { 1320, 234, 453, 345 } ,{ 450, 1230, 378, 356 } ,{ 890, 353, 234, 667 } ,{ 390, 231, 553, 453 } }; String[] rowKeys = { "苹果", "香蕉", "橘子", "梨子" }; String[] columnKeys = { "深圳", "上海", "北京", "杭州" }; CategoryDataset dataset = DatasetUtilities .createCategoryDataset(rowKeys, columnKeys, data); JFreeChart chart = ChartFactory.createBarChart3D("水果销售统计图", "水果", "销售", dataset, PlotOrientation.VERTICAL, true, true, true); CategoryPlot plot=chart.getCategoryPlot(); // 设置网格背景颜色 plot.setBackgroundPaint(Color.GRAY); // 设置网格竖线颜色 plot.setDomainGridlinePaint(Color.RED); // 设置网格横线颜色 plot.setRangeGridlinePaint(Color.YELLOW);
// 显示每个柱的数值,并修改该数值的字体属性 BarRenderer3D renderer=new BarRenderer3D(); renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); renderer.setBaseItemLabelsVisible(true);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); renderer.setItemLabelAnchorOffset(10D);
// 设置平行柱的之间距离 renderer.setItemMargin(0.4);
plot.setRenderer(renderer); String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, null, session); return fileName; }
} |
生成如下图
饼状图实例
创建PieChart01.java
public static String getPicChart(HttpSession session) throws Exception { DefaultPieDataset dataset = new DefaultPieDataset(); // 默认的饼 dataset.setValue("矿难", 2345); dataset.setValue("醉驾", 345); dataset.setValue("城管强拆", 3420); dataset.setValue("医疗事故", 980); dataset.setValue("其他", 934); JFreeChart chart = ChartFactory.createPieChart("非正常死亡人数分布图", dataset , true, true, true);
// 副标题 chart.addSubtitle(new TextTitle("2019年度")); PiePlot pieplot = (PiePlot) chart.getPlot(); pieplot.setLabelFont(new Font("宋体", 0, 11)); // 设置饼图是圆的(true),还是椭圆的(false);默认为true pieplot.setCircular(true); // 没有数据的时候显示的内容 pieplot.setNoDataMessage("无数据显示"); StandardPieSectionLabelGenerator standarPieIG = new StandardPieSectionLabelGenerator ("{0}:({1}人.{2})",NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()); pieplot.setLabelGenerator(standarPieIG); //突出显示 pieplot.setExplodePercent("城管强拆", 0.23);
String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, null, session); return fileName; } |
创建页面piechart01.jsp
<% String fileName = PieChart01.getPicChart(session); System.out.println("生成的文件:"+fileName); %> <img alt="fuck" src="DisplayChart?filename=<%=fileName%>" width="700" height="500"> |
生成效果图如下
|
3D饼状图
创建PieChart03.java
public static String getPicChart(HttpSession session) throws Exception { DefaultPieDataset dataset = new DefaultPieDataset(); // 默认的饼 dataset.setValue("矿难", 2345); dataset.setValue("醉驾", 345); dataset.setValue("城管强拆", 3420); dataset.setValue("医疗事故", 980); dataset.setValue("其他", 934); JFreeChart chart = ChartFactory.createPieChart3D("非正常死亡人数分布图", dataset , true, true, true); // 副标题 chart.addSubtitle(new TextTitle("2013年度")); PiePlot pieplot = (PiePlot) chart.getPlot(); pieplot.setLabelFont(new Font("宋体", 0, 11)); // 设置饼图是圆的(true),还是椭圆的(false);默认为true pieplot.setCircular(true);
// 没有数据的时候显示的内容 pieplot.setNoDataMessage("无数据显示"); StandardPieSectionLabelGenerator standarPieIG = new StandardPieSectionLabelGenerator ("{0}:({1}.{2})", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()); pieplot.setLabelGenerator(standarPieIG);
PiePlot3D pieplot3d = (PiePlot3D) chart.getPlot(); // 设置开始角度 pieplot3d.setStartAngle(120D); // 设置方向为”顺时针方向“ pieplot3d.setDirection(Rotation.CLOCKWISE); // 设置透明度,0.5F为半透明,1为不透明,0为全透明 pieplot3d.setForegroundAlpha(0.7F);
String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, null, session); return fileName; } |
创建piechart03.jsp
<% String fileName = PieChart03.getPicChart(session); System.out.println("生成的文件:"+fileName); %> <img alt="fuck" src="DisplayChart?filename=<%=fileName%>" width="700" height="500"> |
折线图(单条)
创建LineChart01.java
public static String getLineChart(HttpSession session) throws Exception { // 访问量统计 TimeSeries timeSeries = new TimeSeries("访问量", Month.class);
// 添加数据 timeSeries.add(new Month(1, 2019), 100); timeSeries.add(new Month(2, 2019), 200); timeSeries.add(new Month(3, 2019), 300); timeSeries.add(new Month(4, 2019), 500); timeSeries.add(new Month(5, 2019), 400); timeSeries.add(new Month(6, 2019), 500); timeSeries.add(new Month(7, 2019), 700); timeSeries.add(new Month(8, 2019), 400); timeSeries.add(new Month(9, 2019), 200); timeSeries.add(new Month(10, 2019), 300); timeSeries.add(new Month(11, 2019), 340); timeSeries.add(new Month(12, 2019), 900);
// 定义时间序列的集合 TimeSeriesCollection lineDataset = new TimeSeriesCollection(); // 将数据添加到序列集合中 lineDataset.addSeries(timeSeries);
// Chart工厂进行加工 JFreeChart chart = ChartFactory.createTimeSeriesChart("访问量时间折线图", "月份", "访问量" ,lineDataset, true, true, true);
// 设置主标题 chart.setTitle(new TextTitle("某网站访问量统计", new Font("隶书", Font.ITALIC, 15))); // 设置子标题 TextTitle subtitle = new TextTitle("2019年度", new Font("黑体", Font.BOLD, 12)); chart.addSubtitle(subtitle); chart.setAntiAlias(true);
// 设置时间轴的范围。 XYPlot plot = (XYPlot) chart.getPlot(); DateAxis dateaxis = (DateAxis) plot.getDomainAxis(); dateaxis.setDateFormatOverride(new java.text.SimpleDateFormat("M月")); dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH, 1));
// 设置曲线是否显示数据点 XYLineAndShapeRenderer xylinerenderer = (XYLineAndShapeRenderer) plot.getRenderer(); xylinerenderer.setBaseShapesVisible(true);
// 设置曲线显示各数据点的值 XYItemRenderer xyitem = plot.getRenderer(); xyitem.setBaseItemLabelsVisible(true); xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER)); xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator()); xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 12)); plot.setRenderer(xyitem);
// 生成文件 String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, session); return fileName; } |
创建linechart01.jsp
<% String fileName = LineChart01.getLineChart(session); System.out.println("生成的文件:"+fileName); %> <img alt="fuck" src="DisplayChart?filename=<%=fileName%>" width="700" height="500"> |
生成效果图如下
折线图(多条)
创建LineChart02.java
public static String getLineChart(HttpSession session) throws Exception { // 访问量统计A网站 TimeSeries timeSeries1 = new TimeSeries("A网站访问量", Month.class); // 添加数据A网站 timeSeries1.add(new Month(1, 2019), 100); timeSeries1.add(new Month(2, 2019), 200); timeSeries1.add(new Month(3, 2019), 300); timeSeries1.add(new Month(4, 2019), 500); timeSeries1.add(new Month(5, 2019), 400); timeSeries1.add(new Month(6, 2019), 500); timeSeries1.add(new Month(7, 2019), 700); timeSeries1.add(new Month(8, 2019), 400); timeSeries1.add(new Month(9, 2019), 200); timeSeries1.add(new Month(10, 2019), 300); timeSeries1.add(new Month(11, 2019), 340); timeSeries1.add(new Month(12, 2019), 900);
// 访问量统计B网站 TimeSeries timeSeries2 = new TimeSeries("B网站访问量", Month.class); // 添加数据B网站 timeSeries2.add(new Month(1, 2019), 234); timeSeries2.add(new Month(2, 2019), 23); timeSeries2.add(new Month(3, 2019), 345); timeSeries2.add(new Month(4, 2019), 654); timeSeries2.add(new Month(5, 2019), 234); timeSeries2.add(new Month(6, 2019), 345); timeSeries2.add(new Month(7, 2019), 454); timeSeries2.add(new Month(8, 2019), 234); timeSeries2.add(new Month(9, 2019), 534); timeSeries2.add(new Month(10, 2019), 980); timeSeries2.add(new Month(11, 2019), 190); timeSeries2.add(new Month(12, 2019), 734);
// 定义时间序列的集合 TimeSeriesCollection lineDataset = new TimeSeriesCollection(); // 将数据添加到序列集合中 lineDataset.addSeries(timeSeries1); lineDataset.addSeries(timeSeries2);
// Chart工厂加工 JFreeChart chart = ChartFactory.createTimeSeriesChart("访问量时间折线图", "月份" , "访问量", lineDataset, true, true, true);
// 设置主标题 chart.setTitle(new TextTitle("A,B网站访问量统计", new Font("隶书", Font.ITALIC, 15))); // 设置子标题 TextTitle subtitle = new TextTitle("2019年度", new Font("黑体", Font.BOLD, 12)); chart.addSubtitle(subtitle); chart.setAntiAlias(true);
// 设置时间轴的范围。 XYPlot plot = (XYPlot) chart.getPlot(); DateAxis dateaxis = (DateAxis) plot.getDomainAxis(); dateaxis.setDateFormatOverride(new java.text.SimpleDateFormat("M月")); dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH, 1));
// 设置曲线是否显示数据点 XYLineAndShapeRenderer xylinerenderer = (XYLineAndShapeRenderer) plot.getRenderer(); xylinerenderer.setBaseShapesVisible(true);
// 设置曲线显示各数据点的值 XYItemRenderer xyitem = plot.getRenderer(); xyitem.setBaseItemLabelsVisible(true); xyitem.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER)); xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator()); xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 12)); plot.setRenderer(xyitem);
// 生成文件 String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 500, session); return fileName; } |
创建linechart02.jsp
<% String fileName = LineChart02.getLineChart(session); System.out.println("生成的文件:"+fileName); %> <img alt="fuck" src="DisplayChart?filename=<%=fileName%>" width="700" height="500"> |
生成效果图如下
|
Struts2结合JfreeChart
创建web动态工程,并导入struts2和Jfreechart所需的jar文件到lib文件夹中
修改web.xml配置文件
<filter> <filter-name>StrutsPrepareAndExecuteFilter</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter>
<filter-mapping> <filter-name>StrutsPrepareAndExecuteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> |
创建BarChartAction.java路径为com.kingsoft.action
public class BarChartAction extends ActionSupport{
private static final long serialVersionUID = -5962944425789298817L;
private JFreeChart chart;
public JFreeChart getChart() { return chart; }
@Override public String execute() throws Exception { double[][] data = { { 1320, 234, 453, 345 }, { 450, 1230, 378, 356 } ,{ 890, 353, 234, 667 }, { 390, 231, 553, 453 } }; String[] rowKeys = { "苹果", "香蕉", "橘子", "梨子" }; String[] columnKeys = { "深圳", "上海", "北京", "杭州" }; CategoryDataset dataset = DatasetUtilities .createCategoryDataset(rowKeys, columnKeys, data); chart = ChartFactory.createBarChart3D("水果销售统计图", "水果", "销售", dataset ,PlotOrientation.VERTICAL ,true, true, true); CategoryPlot plot=chart.getCategoryPlot(); // 设置网格背景颜色 plot.setBackgroundPaint(Color.GRAY); // 设置网格竖线颜色 plot.setDomainGridlinePaint(Color.RED); // 设置网格横线颜色 plot.setRangeGridlinePaint(Color.YELLOW);
// 显示每个柱的数值,并修改该数值的字体属性 BarRenderer3D renderer=new BarRenderer3D(); renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); renderer.setBaseItemLabelsVisible(true);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition (ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); renderer.setItemLabelAnchorOffset(10D);
// 设置平行柱的之间距离 renderer.setItemMargin(0.4);
plot.setRenderer(renderer); return SUCCESS; } } |
在src根目录下创建struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts> <package name="jfreechart" extends="jfreechart-default"> //固定写法 <action name="barChart" class="com.kingsoft.action.BarChartAction"> //name调用时 <result name="success" type="chart"> <param name="value">chart</param> <param name="type">png</param> <param name="width">700</param> <param name="height">500</param> </result> </action> </package> </struts> |
创建一个页面用于展示图片
<body> <img alt="" src="barChart"> </body> |
启动时输入地址http://localhost:8080/strutsjfreechart/index.jsp
|