JFreeChart基础

JFreeChart

JFreeChart是JAVA平台上的一个开放的图表绘制类库。它完全使用JAVA语言编写,是为applications, applets, servlets 以及JSP等使用所设计。

JFreeChart可生成饼图(pie charts)、柱状图(bar charts)、散点图(scatter plots)、时序图(time series)、甘特图(Gantt charts)等等多种图表,并且可以产生PNG和JPEG格式的输出,还可以与PDF和EXCEL关联。

引用
BarChart
  • 在web.xml中添加映射
<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>
  • BarChartDemo.java文件中定义图表
public class BarChartDemo {

	public static String getBarChart(HttpSession session) throws Exception {
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		dataset.addValue(510, "sz", "apple");
		dataset.addValue(320, "sz", "banana");
		dataset.addValue(450, "sz", "orange");
		dataset.addValue(404, "gz", "apple");
		dataset.addValue(320, "gz", "banana");
		dataset.addValue(450, "gz", "orange");
		JFreeChart chart = ChartFactory.createBarChart3D("friut sale", "friut", "sales", dataset);
		String filename = ServletUtilities.saveChartAsPNG(chart, 700, 500, session);
		return filename;
	}
}
  • WebContent中写barChart.jsp
<%@page import="com.redsheep.chart.bar.BarChartDemo"%>
<body>
<%
	String filename=BarChartDemo.getBarChart(session);
	System.out.println(filename);
%>
<img src="DisplayChart?filename=<%=filename%>" width="700" height="500" border=0/>
</body>
  • 运行效果
    在这里插入图片描述
Pie Chart
  • PieChartDemo.java
public class PieChart3 {

	public static String getPieChart(HttpSession session) throws Exception {
		DefaultPieDataset dataset = new DefaultPieDataset();
		dataset.setValue("黑心矿难", 1000);
		dataset.setValue("醉酒驾驶", 800);
		dataset.setValue("城管强拆", 400);
		dataset.setValue("医疗事故", 100);
		dataset.setValue("其他", 29);

		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;
	}
  • pieChart.jsp
<%@page import="com.java1234.chart.pie.PieChartDemo"%>
<body>
<%
	String fileName=PieChart3.getPieChart(session);
	System.out.println(fileName);
%>
<img src="DisplayChart?filename=<%=fileName %>" width="700" height="500" border="0"/>
</body>
  • 运行效果
    在这里插入图片描述
乱码问题
  • 更改jfreechart版本(最简单省心,但不是特别推荐)

一般使用jfreechart-1.0.10.jar以上的版本都有可能出现这个问题,改成1.0.10及以下的版本即可。

  • 设置主题样式(比较简单,推荐)
// 创建主题样式
StandardChartTheme mChartTheme = new StandardChartTheme("CN");
// 设置标题字体
mChartTheme.setExtraLargeFont(new Font("黑体", Font.BOLD, 20));
// 设置轴向字体
mChartTheme.setLargeFont(new Font("宋体", Font.CENTER_BASELINE, 15));
// 设置图例字体
mChartTheme.setRegularFont(new Font("宋体", Font.CENTER_BASELINE, 15));
// 应用主题样式
ChartFactory.setChartTheme(mChartTheme);

运行效果如下:

在这里插入图片描述

  • 分别设置横轴、纵轴、副标题的字体(可以结合主题样式的方法,对大部分字体统一设置,对特殊字体单独设置)
// 副标题
chart.addSubtitle(new TextTitle("2013年度"));
TextTitle mTextTitle = chart.getTitle();
mTextTitle.setFont(new Font("微软雅黑", Font.PLAIN, 30));

运行效果

在这里插入图片描述

//简洁的写法
chart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 10));

运行效果

在这里插入图片描述

Line Chart
  • LineChartDemo.java
public class LineChartDemo {
	public static String genLineChart(HttpSession session) throws Exception {

        // 创建主题样式
		StandardChartTheme mChartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		mChartTheme.setExtraLargeFont(new Font("黑体", Font.BOLD, 20));
		// 设置轴向字体
		mChartTheme.setLargeFont(new Font("宋体", Font.CENTER_BASELINE, 15));
		// 设置图例字体
		mChartTheme.setRegularFont(new Font("宋体", Font.CENTER_BASELINE, 15));
		// 应用主题样式
		ChartFactory.setChartTheme(mChartTheme);
        
		// 访问量统计
		TimeSeries timeSeries = new TimeSeries("A网站访问量统计", Month.class);
		// 添加数据
		timeSeries.add(new Month(1, 2013), 100);
		timeSeries.add(new Month(2, 2013), 200);
		timeSeries.add(new Month(3, 2013), 300);
		timeSeries.add(new Month(4, 2013), 400);
		timeSeries.add(new Month(5, 2013), 560);
		timeSeries.add(new Month(6, 2013), 600);
		timeSeries.add(new Month(7, 2013), 750);
		timeSeries.add(new Month(8, 2013), 890);
		timeSeries.add(new Month(9, 2013), 120);
		timeSeries.add(new Month(10, 2013), 400);
		timeSeries.add(new Month(11, 2013), 1200);
		timeSeries.add(new Month(12, 2013), 1600);

		// 访问量统计
		TimeSeries timeSeries2 = new TimeSeries("B网站访问量统计", Month.class);
		// 添加数据
		timeSeries2.add(new Month(1, 2013), 50);
		timeSeries2.add(new Month(2, 2013), 100);
		timeSeries2.add(new Month(3, 2013), 150);
		timeSeries2.add(new Month(4, 2013), 200);
		timeSeries2.add(new Month(5, 2013), 220);
		timeSeries2.add(new Month(6, 2013), 300);
		timeSeries2.add(new Month(7, 2013), 340);
		timeSeries2.add(new Month(8, 2013), 400);
		timeSeries2.add(new Month(9, 2013), 450);
		timeSeries2.add(new Month(10, 2013), 500);
		timeSeries2.add(new Month(11, 2013), 70);
		timeSeries2.add(new Month(12, 2013), 800);

		// 定义时间序列的集合
		TimeSeriesCollection lineDataset = new TimeSeriesCollection();
		lineDataset.addSeries(timeSeries);
		lineDataset.addSeries(timeSeries2);

		JFreeChart chart = ChartFactory.createTimeSeriesChart("访问量统计时间折线图", "月份", "访问量", lineDataset, true, true, true);

		chart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 10));

		// 设置主标题
		chart.setTitle(new TextTitle("A,B网站访问量统计对比图", new Font("隶书", Font.ITALIC, 15)));
		// 设置子标题
		TextTitle subtitle = new TextTitle("2013年度", 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;
	}
}
  • lineChart.jsp
<%@page import="com.redsheep.chart.bar.LineChartDemo"%>
<body>
<%
	String fileName=LineChartDemo.genLineChart(session);
	System.out.println(fileName);
%>
<img src="DisplayChart?filename=<%=fileName %>" width="700" height="500" border="0"/>
  • 运行效果

在这里插入图片描述

Structs2 JFreeChart

Struts2中整合了JFreeChart的功能,使用起来更便捷。

  • 添加Structs2的包

struts官网下载,在其中找到核心包、jfreechart支持包、常用包,添加到WEB-INF下的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中写入图表,可到structs官网查看demo。
public class BarChartAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JFreeChart chart;

	public JFreeChart getChart() {
		return chart;
	}

	@Override
	public String execute() throws Exception {
		double[][] data = new double[][] { { 1320, 1110, 1123, 321 }, { 720, 210, 1423, 1321 }, { 830, 1310, 123, 521 },
				{ 400, 1110, 623, 321 } };
		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.white);
		// 设置网格竖线颜色
		plot.setDomainGridlinePaint(Color.pink);
		// 设置网格横线颜色
		plot.setRangeGridlinePaint(Color.pink);

		// 显示每个柱的数值,并修改该数值的字体属性
		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;
	}

}
  • 配置struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<struts>
	<package name="jfreechart" extends="jfreechart-default">
		<action name="barChart" class="com.redsheep.chart.bar.BarChartAction">
			<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>
  • 在jsp中调用该图表
<body>
<img src="barChart"/>
</body>
  • 运行效果
    在这里插入图片描述
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值