【Java图表绘制-JFreeChart】

本文介绍了Java中常用的图表库,如JopenChart、ChartDirector、Eclipse BIRT和iReport。重点讲解了JFreeChart,包括其简介、评价、官网链接和版本信息,以及如何用JFreeChart绘制柱状图、饼状图和折线图的实例,特别提到了Struts2集成JFreeChart的方法。

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

个人学习整理,如有不足之处,请不吝指教。转载请注明:@CSU-Max


一些常用的支持 Java 的图表类库

JopenChart

JopenChart 是一个开放源代码的Java库,它还是一个可以用来创建不同种类图表并且将它们内嵌到web或者Swing应用程序中的工具。它甚至还能够支持插入数据和绘制数学函数。

项目主页:http://jopenchart.sourceforge.net/

ChartDirector

ChartDirector控件使用方便,快捷,灵活,功能强大,交互性强。在web服务器以及嵌入式应用程序开发中,它是一种非常理想的工具,拥有丰富的图表图形组件库。

项目主页: http://www.advsofteng.com/

Eclipse BIRT

BIRT是一个Eclipse-based开放源代码报表系统。它主要是用在基于Java与J2EE的Web应用程序上。BIRT主要由两部分组成:一个是基于Eclipse的报表设计和一个可以加到你应用服务的运行期组件。BIRT同时也提供一个图形报表制作引擎。

项目主页: https://www.eclipse.org/birt/phoenix/

iReport

iReport 是用于定义 JasperReport 报表的可视化工具,JasperReport使用XML来定义一个报表的结构,iReport可以让用户很方便地定义报表,而不需要手工去写这些XML文件

项目主页: http://community.jaspersoft.com/project/ireport-designer


JFreeChart 简介

介绍

       JFreeChart是开放源代码站点 SourceForge.net 上的 Java 平台上的一个开放的图表绘制类库。它完全使用JAVA语言编写,是为applications, applets, servlets 以及JSP等使用所设计。JFreeChart可生成饼图(pie charts)、柱状图(bar charts)、散点图(scatter plots)、时序图(time series)、甘特图(Gantt charts)等等多种图表,并且可以产生PNG和JPEG格式的输出,还可以与PDFEXCEL关联。

评价

    简单易学;免费开源,但是开发手册和示例需付费;是一款轻量级的开源库,稳定且功能强大;生成的图表运行顺畅;

    交互性不强;文字和图片不是很清楚。

官网及版本

http://www.jfree.org/jfreechart/        

目前最新版本 :jfreechart-1.0.17     (点击即可下载)       文章所用版本:  jfreechart-1.0.10      新版本可能会出现中文乱码问题


几种常见图表的绘制

柱状图

servlet + JFreeChart 绘制柱状图-1

导入相应的 jar 包

相关 jar 包下载

修改 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>
               
编写类

public class BarChartDemo {

public static String getBarChart(HttpSession session) throws Exception {

//使用默认的数据集

DefaultCategoryDataset dataset = new DefaultCategoryDataset();

//向数据集中模拟添加数据

dataset.addValue(8000, "深圳", "测试员");

dataset.addValue(12000, "深圳", "软件工程师");

dataset.addValue(15000, "深圳", "需求分析师");

dataset.addValue(9000, "深圳", "系统维护员");

JFreeChart chart=ChartFactory.createBarChart3D("深圳IT行业各职业平均工资统计图", "职位", "工资/元", dataset,

PlotOrientation.VERTICAL, true, true, true);

//生成指定格式的图片,得到文件名

String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, null,session);

return fileName;

}

}

页面文件

<%@page import="com.csumax.Demo.BarChartDemo"%>

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Insert title here</title>

</head>

<body>

<%

	String fileName=BarChartDemo.getBarChart(session);

	System.out.println(fileName);

%>

<img src="DisplayChart?filename=<%=fileName %>" width="700" height="500" border="0"/>

</body>

</html>

页面生成的图片


servlet + JFreeChart 绘制柱状图-2

public class BarChartDemo {

public static String getBarChart(HttpSession session) throws Exception {

double [][]data=new double[][]{{9000,8500,10000,6000},{12000,11500,11000,9000},{9000,9500,8000,4000},{7000,7500,9000,8000}};

String []rowKeys={"测试员","软件工程师","需求分析师","系统维护员"};

String []columnKeys={"深圳","杭州","上海","南京"};

CategoryDataset dataset=DatasetUtilities.createCategoryDataset(rowKeys,columnKeys ,data);

JFreeChart chart=ChartFactory.createBarChart3D("各城市IT职业者工资统计图", "职位", "工资/元", dataset,

PlotOrientation.VERTICAL, true, true, true);

String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, null,session);

return fileName;

}

}

页面生成的图片

Struts2 + JFreeChart 绘制柱状图

将 JFreeChart 的包和 Struts2 的包导入到 lib 文件夹下:

相关 jar 文件下载:    JFreeChart 相关 jar 包  和 struts2 相关 jar 包

修改 web.xml 文件

主要是为了加入struts2

 <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>

编写 Action 类

public class BarCharAction 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 文件,并进行配置
<package name="jfreechart" extends="jfreechart-default">
        <!-- 显示柱状图 -->
        <action name="barChart" class="com.csumax.action.BarCharAction">
            <result name="success" type="chart">
                <!-- 返回 Action 中生成的 chart --> 
                <param name="value">chart</param>
                <!-- 返回的图片格式要个 Action 中生成的格式一样 --> 
                <param name="type">png</param>
                <!-- 设置生产图片的大小 --> 
                <param name="width">700</param>
                <param name="height">500</param>
            </result>
        </action>
 </package>

注意此处 要继承 jfreechart-default 包,与一般使用 struts2 不同。

编写页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>统计表初级测试</title>
    </head>
    <body>
        <!--在页面请求action-->
        <img src="barChart.action" />

        <div style="height: 50px; width =400px; background-color: gray">
            <a href="bar.jsp">查看柱状统计图</a>
            <a href="line.jsp">查看折现统计图</a>
            <a href="pie.jsp">查看饼状统计图</a>
            
        </div>
    </body>
</html>
效果


饼状图

Struts2 + JFreeChart 绘制饼状图

public class PieCharAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private JFreeChart chart;
    public JFreeChart getChart() {
        return chart;
    }
    @Override
    public String execute() throws Exception {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("华为", 100);
        dataset.setValue("腾讯", 200);
        dataset.setValue("新浪", 160);
        dataset.setValue("百度", 120);
        dataset.setValue("阿里巴巴", 150);
        chart = ChartFactory.createPieChart3D("各大公司招聘人数统计表", dataset,
                true, true, true);

        // 以下为格式设置,具体的可以查API
        // 副标题
        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);
        return SUCCESS;
    }
}

其他部分参考上文的配置修改即可,再次不赘述。

效果


折线图

Struts2 + JFreeChart 绘制折线图

public class LineCharAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private JFreeChart chart;
    public JFreeChart getChart() {
        return chart;
    }
    @Override
    public String execute() throws Exception {
        // 收入统计
        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);
        chart = ChartFactory.createTimeSeriesChart("收入统计折线图", "月份", "收入/K元",
                lineDataset, true, true, true);

        // 以下为格式设置,具体的可以查API        
        // 设置主标题
        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);
        return SUCCESS;
    }
}

其他部分参考上文的配置修改即可,再次不赘述。

效果



附注:

struts.xml 中要继承 jfreechart-default 包

尽量不要使用最新版本,可能会出现中文乱码问题,一般使用稳定版本。





评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值