Java绘制图表(柱状图、饼图、折线图(时间序列操作)):开放的图表绘制类库JFreeChart(Servlet篇)

本文详细介绍如何使用JFreeChart在Java中绘制柱状图、饼图和折线图,包括项目搭建、数据集创建、图表定制及展示过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java绘制图表(柱状图、饼图、折线图(时间序列操作)):开放的图表绘制类库JfreeChart(Servlet篇)

操作步骤:

1、新建Dynamic Web项目。
2、导入JFreeChart所需的jar包。
3、在web.xml文件中配置servlet(根据请求调用JFreeChart显示图表的DisplayChart类)。
4、编写生成图表的Java类。
<1>建立数据集(DefaultCategoryDataSet、等方式)。
<2>使用JFreeChart的工厂类根据数据集生成图表。
<3>使用ServletUtilities工具类的saveChartAsPNG()方法生成图表的png图片文件名(即fileName)。
5、根据servlet中配置的jsp页面名称新建jsp页面,在页面中请求第4步中的Java类得到fileName进行显示图表。
6、部署该项目到tomcat服务器,在浏览器请求jsp页面即可。

实例1:BarChart(柱状图)

1、新建Dynamic Web项目。

关于web项目创建后WEB-INF下面没有出现web.xml的解决方法https://blog.youkuaiyun.com/weixin_43209201/article/details/86607913

2、导入JFreeChart所需的jar包。

jar包下载地址:https://sourceforge.net/projects/jfreechart/files/

下载的压缩包解压后在下图所示路径寻找jar包:
在这里插入图片描述
将jar包导入项目中(复制粘贴即可),有的jar包可能用不到,为了方便这几全部导入了:
在这里插入图片描述
3、在web.xml文件中配置servlet(根据请求调用JFreeChart显示图表的DisplayChart类)。代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
	version="4.0">
	<display-name>JFreeChart_Demo</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<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>
</web-app>

4、编写生成图表的Java类。
<1>建立数据集(DefaultCategoryDataSet、等方式)。
<2>使用JFreeChart的工厂类根据数据集生成图表。
<3>使用ServletUtilities工具类的saveChartAsPNG()方法生成图表的png图片,返回图片的文件名(即fileName)。代码如下:

这里根据Dataset的不同封装方式采用两种实现方式,分别为使用DefaultCategoryDataset类生成柱状图和使用DatasetUtilities工具类生成柱状图并进行美化。

使用DefaultCategoryDataset类生成柱状图:

package chart;

import java.awt.Font;
import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 * 使用DefaultCategoryDataset类生成柱状图
 * 
 * @author lingtouyang的csdn博客 ▄┻┳═一 ☆
 *
 */
public class BarChart_ByDefaultCategoryDataset {

	public static String generateBarChart(HttpSession session) throws IOException {

		/**
		 * 以下代码通过设置主题样式解決中文乱码问题
		 */
		// 创建主题样式
		StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
		// 设置图例的字体
		standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
		// 设置轴向的字体
		standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
		// 应用主题样式
		ChartFactory.setChartTheme(standardChartTheme);

		// 采用默认类别数据集采集数据
		DefaultCategoryDataset defaultDataSet = new DefaultCategoryDataset();
		defaultDataSet.setValue(9.89, "抖音用户占比", "广东省");// 数据 比较的内容 比较的分类
		defaultDataSet.setValue(7.21, "抖音用户占比", "江苏省");
		defaultDataSet.setValue(6.90, "抖音用户占比", "山东省");
		defaultDataSet.setValue(5.85, "抖音用户占比", "河南省");
		defaultDataSet.setValue(5.49, "抖音用户占比", "浙江省");
		// 调用ChartFactory工厂类生成3D柱状图
		JFreeChart barChart = ChartFactory.createBarChart3D("抖音用户地域分布占比TOP5", // 柱状图标题
				"地区", // 比较的分类标签
				"所占比(单位:%)", // 比较的内容标签
				defaultDataSet // 数据集
		);
		// 使用ServletUtilities将工厂类生成的图表保存为png图片
		String fileName = ServletUtilities.saveChartAsPNG(barChart, // 工厂类生成的图表
				700, // 要生成图片宽度
				500, // 要生成图片的高度
				session // HttpSession
		);

		// 返回图片的文件名
		return fileName;

	}

}

使用DatasetUtilities工具类生成柱状图并进行美化:

package chart;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.ui.TextAnchor;

/**
 * 使用DatasetUtilities工具类生成柱状图并进行美化
 * 
 * @author lingtouyang的csdn博客 ▄┻┳═一 ☆
 *
 */
public class BarChart_ByDatasetUtilities {

	public static String generateBarChart(HttpSession session) throws IOException {
		/**
		 * 以下代码通过设置主题样式解決中文乱码问题
		 */
		// 创建主题样式
		StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
		// 设置图例的字体
		standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
		// 设置轴向的字体
		standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
		// 应用主题样式
		ChartFactory.setChartTheme(standardChartTheme);

		double[][] data = new double[][] { { 1310, 720, 1130, 440 }, { 1220, 700, 1020, 400 }, { 1110, 680, 980, 360 },
				{ 1000, 640, 800, 600 } };
		String[] rowKeys = new String[] { "猪肉", "牛肉", "鸡肉", "鱼肉" };
		String[] columnKeys = new String[] { "广州", "深圳", "东莞", "佛山" };
		// 利用DatasetUtilities工具类创建CategoryDataset
		CategoryDataset dataSet = DatasetUtilities.createCategoryDataset(rowKeys, // 比较的内容数组(肉类)
				columnKeys, // 比较的分类数组(地区分类)
				data // 比较的数据
		);
		// 调用ChartFactory工厂类生成3D柱状图
		JFreeChart barChart = ChartFactory.createBarChart("肉类销量统计图", // 图表的标题
				"地区", // 比较的分类标签
				"销量", // 比较的内容标签
				dataSet, // 比较的数据集
//    		PlotOrientation.HORIZONTAL,		//图表显示方向:水平方向
				PlotOrientation.VERTICAL, // 图表显示方向:垂直方向(默认)
				true, // a flag specifying whether or not a legend is required
				true, // configure chart to generate tool tips
				true // configure chart to generate URLs
		);

		/**
		 * 设置图表样式:通过matlab的plot()函数设置图表样式,使得图表更加美观
		 */
		CategoryPlot plot = barChart.getCategoryPlot();
		// 设置网格背景颜色
		plot.setBackgroundPaint(Color.WHITE);
		// 设置网格竖线颜色
		plot.setDomainGridlinePaint(Color.PINK);
		// 设置网格横线颜色
		plot.setRangeGridlinePaint(Color.pink);

		// 显示每个柱的数值,并修改数值的字体属性(renderer渲染器)
		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);
		// 将样式应用到CategoryPlot
		plot.setRenderer(renderer);

		// 使用ServletUtilities将工厂类生成的图表保存为png图片
		String fileName = ServletUtilities.saveChartAsPNG(barChart, // 工厂类生成的图表
				700, // 要生成图片宽度
				500, // 要生成图片的高度
				session // HttpSession
		);

		// 返回图片的文件名
		return fileName;
	}
}

5、根据servlet中配置的jsp页面名称新建jsp页面,在页面中请求第4步中的Java类得到fileName进行显示图表。
barChart_ByDefaultCategoryDataset.jsp:

<%@page import="chart.BarChart_ByDefaultCategoryDataset"%>    <!-- 注意导包 -->
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String fileName = BarChart_ByDefaultCategoryDataset.generateBarChart(session); //调用生成图表的Java类,返回柱状图png文件的文件名
	%>
	<!--设置图片路径:(servlet的url-pattern)?filename=(上面获取的文件名fileName)  -->
	<img src="displayChart?filename=<%=fileName%>" width="700"
		height="500" border="0">
</body>
</html>

barChart_ByDatasetUtilities.jsp:

<%@page import="chart.BarChart_ByDatasetUtilities"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String fileName = BarChart_ByDatasetUtilities.generateBarChart(session); //调用生成图表的Java类,返回柱状图png文件的文件名
	%>
	<!--设置图片路径:(servlet的url-pattern)?filename=(上面获取的文件名fileName)  -->
	<img src="displayChart?filename=<%=fileName%>" width="700"
		height="500" border="0">
</body>
</html>

6、部署该项目到tomcat服务器,在浏览器请求对应的jsp页面即可。
使用DefaultCategoryDataset类生成柱状图效果图如下:
在这里插入图片描述
使用DatasetUtilities工具类生成柱状图效果图如下:
在这里插入图片描述
使用DatasetUtilities工具类生成柱状图并进行美化后的效果图如下:
在这里插入图片描述

实例2:PieChart(饼图)

与实例1柱状图的生成类似的步骤
1、新建Dynamic Web项目。
2、导入JFreeChart所需的jar包。
3、在web.xml文件中配置servlet(根据请求调用JFreeChart显示图表的DisplayChart类)。代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
	version="4.0">
	<display-name>JFreeChart_Demo</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<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>
</web-app>

4、编写生成图表的Java类。
<1>建立数据集(DefaultCategoryDataSet、等方式)。
<2>使用JFreeChart的工厂类根据数据集生成图表。
<3>使用ServletUtilities工具类的saveChartAsPNG()方法生成图表的png图片,返回图片的文件名(即fileName)。
这里根据拼图的2D和3D效果采用两种实现方式。代码分别如下:
2D效果:

package chart;

import java.awt.Font;
import java.text.NumberFormat;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
/**
 * JFreeChart产生2D的饼图
 * 
 * @author lingtouyang的csdn博客 ▄┻┳═一 ☆
 *
 */
public class PieChart_2D {

	public static String generatePieChart(HttpSession session) throws Exception {

		/**
		 * 以下代码通过设置主题样式解決中文乱码问题
		 */
		// 创建主题样式
		StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
		// 设置图例的字体
		standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
		// 设置轴向的字体
		standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
		// 应用主题样式
		ChartFactory.setChartTheme(standardChartTheme);

		// 采用默认类别数据集采集数据
		DefaultPieDataset dataset = new DefaultPieDataset();
		dataset.setValue("黑心矿难", 900);
		dataset.setValue("醉酒驾驶", 800);
		dataset.setValue("城管强拆", 400);
		dataset.setValue("医疗事故", 100);
		dataset.setValue("其他", 29);

		// 调用ChartFactory工厂类生成饼图
		JFreeChart chart = ChartFactory.createPieChart(
				"2018年度非正常死亡人数分布图", // 图表的标题
				dataset, // 比较的数据集
				true, // a flag specifying whether or not a legend is required
				true, // configure chart to generate tool tips
				true // configure chart to generate URLs
		);

		// 设置副标题
		chart.addSubtitle(new TextTitle("————此数据纯属虚构,无任何依据"));

		/**
		 * 设置图表样式:通过matlab的plot()函数设置图表样式,使得图表更加美观
		 */
		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);

		// 使用ServletUtilities将工厂类生成的图表保存为png图片
		String fileName = ServletUtilities.saveChartAsPNG(
				chart, // 工厂类生成的图表
				700, // 要生成图片宽度
				500, // 要生成图片的高度
				null, // 设置渲染器
				session // HttpSession
		);
		// 返回图片的文件名
		return fileName;
	}
}

3D效果:

package chart;

import java.awt.Font;
import java.text.NumberFormat;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.util.Rotation;
/**
 * JFreeChart产生3D的饼图
 * 
 * @author lingtouyang的csdn博客 ▄┻┳═一 ☆
 *
 */
public class PieChart_3D {

	public static String generatePieChart(HttpSession session) throws Exception {

		/**
		 * 以下代码通过设置主题样式解決中文乱码问题
		 */
		// 创建主题样式
		StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
		// 设置图例的字体
		standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
		// 设置轴向的字体
		standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
		// 应用主题样式
		ChartFactory.setChartTheme(standardChartTheme);
		
		// 采用默认类别数据集采集数据
		DefaultPieDataset dataset = new DefaultPieDataset();
		dataset.setValue("黑心矿难", 900);
		dataset.setValue("醉酒驾驶", 800);
		dataset.setValue("城管强拆", 400);
		dataset.setValue("医疗事故", 100);
		dataset.setValue("其他", 29);

		// 调用ChartFactory工厂类生成饼图
		JFreeChart chart = ChartFactory.createPieChart3D(
				"2018年度非正常死亡人数分布图", // 图表的标题
				dataset, // 比较的数据集
				true, // a flag specifying whether or not a legend is required
				true, // configure chart to generate tool tips
				true // configure chart to generate URLs
		);

		// 设置副标题
		chart.addSubtitle(new TextTitle("————此数据纯属虚构,无任何依据"));

		/**
		 * 设置图表样式:通过matlab的plot()函数设置图表样式,使得图表更加美观
		 */
		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})",	//labelFormat the label format string (null notpermitted).
				NumberFormat.getNumberInstance(),//numberFormat the format object for the values (nullnot permitted).
				NumberFormat.getPercentInstance()//percentFormat the format object for the percentages(null not permitted).
				);
		pieplot.setLabelGenerator(standarPieIG);
		// 设置突出显示无效的?
		pieplot.setExplodePercent("城管强拆", 0.23);

		// 设置3D显示样式
		PiePlot3D pieplot3d = (PiePlot3D) chart.getPlot();
		// 设置开始角度
		pieplot3d.setStartAngle(120D);
		// 设置方向为”顺时针方向“
		pieplot3d.setDirection(Rotation.CLOCKWISE);
		// 设置透明度,0.5F为半透明,1为不透明,0为全透明
		pieplot3d.setForegroundAlpha(0.7F);

		// 使用ServletUtilities将工厂类生成的图表保存为png图片
		String fileName = ServletUtilities.saveChartAsPNG(
				chart, // 工厂类生成的图表
				700, // 要生成图片宽度
				500, // 要生成图片的高度
				null, // 设置渲染器
				session // HttpSession
		);
		// 返回图片的文件名
		return fileName;
	}
}

5、根据servlet中配置的jsp页面名称新建jsp页面,在页面中请求第4步中的Java类得到fileName进行显示图表。代码如下:
2D:

<%@page import="chart.PieChart_2D"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String fileName = PieChart_2D.generatePieChart(session); //调用生成图表的Java类,返回饼图png文件的文件名
	%>
	<!--设置图片路径:(servlet的url-pattern)?filename=(上面获取的文件名fileName)  -->
	<img src="displayChart?filename=<%=fileName%>" width="700" height="500"
		border="0">
</body>
</html>

3D:

<%@page import="chart.PieChart_3D"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String fileName = PieChart_3D.generatePieChart(session); //调用生成图表的Java类,返回饼图png文件的文件名
	%>
	<!--设置图片路径:(servlet的url-pattern)?filename=(上面获取的文件名fileName)  -->
	<img src="displayChart?filename=<%=fileName%>" width="700" height="500"
		border="0">
</body>
</html>

6、部署该项目到tomcat服务器,在浏览器请求相应的jsp页面即可。

2D效果:
在这里插入图片描述

3D效果:
在这里插入图片描述

实例3:LineChart(折线图(包含对时间序列操作))

与实例1柱状图的生成类似的步骤
1、新建Dynamic Web项目。
2、导入JFreeChart所需的jar包。
3、在web.xml文件中配置servlet(根据请求调用JFreeChart显示图表的DisplayChart类)。代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
	version="4.0">
	<display-name>JFreeChart_Demo</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<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>
</web-app>

4、编写生成图表的Java类。
<1>建立数据集(DefaultCategoryDataSet、等方式)。
<2>使用JFreeChart的工厂类根据数据集生成图表。
<3>使用ServletUtilities工具类的saveChartAsPNG()方法生成图表的png图片,返回图片的文件名(即fileName)。代码如下:

package chart;

import java.awt.Font;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.TextAnchor;

/**
 * JFreeChart产生折线图
 * 
 * @author lingtouyang的csdn博客 ▄┻┳═一 ☆
 *
 */
public class LineChart {
	
	public static String generateLineChart(HttpSession session)throws Exception{
		/**
		 * 以下代码通过设置主题样式解決中文乱码问题
		 */
		// 创建主题样式
		StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
		// 设置图例的字体
		standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
		// 设置轴向的字体
		standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
		// 应用主题样式
		ChartFactory.setChartTheme(standardChartTheme);

		// 访问量统计
		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.setTitle(new TextTitle("A,B网站访问量统计对比图", new Font("隶书", Font.ITALIC, 15))); 
		//设置子标题
		TextTitle subtitle = new TextTitle("2018年度", 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;
}
}

5、根据servlet中配置的jsp页面名称新建jsp页面,在页面中请求第4步中的Java类得到fileName进行显示图表。代码如下:

<%@page import="chart.LineChart"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String fileName = LineChart.generateLineChart(session); //调用生成图表的Java类,返回饼图png文件的文件名
	%>
	<!--设置图片路径:(servlet的url-pattern)?filename=(上面获取的文件名fileName)  -->
	<img src="displayChart?filename=<%=fileName%>" width="700" height="500"
		border="0">
</body>
</html>

6、部署该项目到tomcat服务器,在浏览器请求相应的jsp页面即可。
在这里插入图片描述
后来看见这个博客写的也挺全:https://www.cnblogs.com/newwind/p/5680389.html
说明:在这里,2D、3D与数据集的封装只是为了分类方便,四者可以两两组合,烦请自行组合。另外,图中数据纯属虚构,不代表任何实际意义。谢谢理解!如有问题欢迎指出!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值