Java绘制图表框架JFreeChart入门

1.下载JFreeChart框架
http://www.jfree.org/jfreechart/

这里下载的是最新版本:JFreeChart 1.0.17


2.使用MyEclipse创建一个web项目,名称为jfreechart,导入第1步下载好的jfreechart并将其中的:jfreechart-1.0.17.jar和jcommon-1.0.21.jar 两个jar包,如下图所示:

Java绘制图表框架JFreeChart入门_第1张图片

3.创建处理绘制图表请求的servlet:JFreeChartServlet ,源码如下:

package org.xjh.jfreechart;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartUtilities;
import org.xjh.web.chart.BarChartTest;
import org.xjh.web.chart.LineChartTest;
import org.xjh.web.chart.PieChartTest;
import org.xjh.web.chart.RingChartTest;

/**
 * 处理绘制图表请求
 * 
 * @author xjh
 * 
 */
public class JFreeChartServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		//根据客户端请求的图表类型,进行相应的图表绘制
		String chartType = request.getParameter("chartType");
		//如果没有提供图表类型
        if(chartType == null || "".equals(chartType.trim())){  
        	//提示错误
        	request.setAttribute("message", "请提供图表类型!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);  
            return;  
        }  
        
		//设置默认图表宽高
		int width = 600;
		int height = 400;
		
		//根据客户端传递过来的宽高设置图表的宽高
		try {
			width = Integer.parseInt(request.getParameter("width"));
			height = Integer.parseInt(request.getParameter("height"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//设置响应的内容类型为图片形式
		response.setContentType("image/png");
		
		//根据客户端请求的图表类型绘制相应的图表
		if ("bar".equals(chartType)) { //柱状图
			BarChartTest t = new BarChartTest();
			ChartUtilities.writeChartAsPNG(response.getOutputStream(),
					t.createBarChart2D(), width, height, null); //将图表转成图片形式

		} else if ("pie".equals(chartType)) { //饼状图
			PieChartTest t = new PieChartTest();
			ChartUtilities.writeChartAsPNG(response.getOutputStream(),
					t.createPieChart(), width, height, null); 

		} else if ("line".equals(chartType)) { //线条图
			LineChartTest t = new LineChartTest();
			ChartUtilities.writeChartAsPNG(response.getOutputStream(),
					t.createLineChart(), width, height, null);

		} else if ("ring".equals(chartType)) { //环状图
			RingChartTest t = new RingChartTest();
			ChartUtilities.writeChartAsPNG(response.getOutputStream(),
					t.createRingChart(), width, height, null);
		}

	}

}

4.分别创建用于绘制“柱状图”、“饼状图”、“线条图”、“环状图”的测试类。

  4.1 绘制柱状图的类的源码

package org.xjh.web.chart;

import java.awt.Color;
import java.awt.GradientPaint;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DatasetUtilities;

/**
 * 柱状图测试
 * @author xjh
 *
 */
public class BarChartTest {

	/**
	 * 得到2D柱状图的数据集合
	 * 
	 * @return
	 */
	private CategoryDataset getDataset2D() {
		String str1 = "First";
		String str2 = "Second";
		String str3 = "Third";
		String str4 = "Category 1";
		String str5 = "Category 2";
		String str6 = "Category 3";
		String str7 = "Category 4";
		String str8 = "Category 5";
		DefaultCategoryDataset localDefaultCategoryDataset = new DefaultCategoryDataset();
		localDefaultCategoryDataset.addValue(1.0D, str1, str4);
		localDefaultCategoryDataset.addValue(4.0D, str1, str5);
		localDefaultCategoryDataset.addValue(3.0D, str1, str6);
		localDefaultCategoryDataset.addValue(5.0D, str1, str7);
		localDefaultCategoryDataset.addValue(5.0D, str1, str8);
		localDefaultCategoryDataset.addValue(5.0D, str2, str4);
		localDefaultCategoryDataset.addValue(7.0D, str2, str5);
		localDefaultCategoryDataset.addValue(6.0D, str2, str6);
		localDefaultCategoryDataset.addValue(8.0D, str2, str7);
		localDefaultCategoryDataset.addValue(4.0D, str2, str8);
		localDefaultCategoryDataset.addValue(4.0D, str3, str4);
		localDefaultCategoryDataset.addValue(3.0D, str3, str5);
		localDefaultCategoryDataset.addValue(2.0D, str3, str6);
		localDefaultCategoryDataset.addValue(3.0D, str3, str7);
		localDefaultCategoryDataset.addValue(6.0D, str3, str8);
		return localDefaultCategoryDataset;
	}

	/**
	 * 创建2D柱状图
	 * 
	 * @param paramCategoryDataset
	 * @return
	 */
	public JFreeChart createBarChart2D() {
		
		//得到2D柱状图的数据集合
		CategoryDataset paramCategoryDataset = getDataset2D();
		
		//创建柱状图
		JFreeChart localJFreeChart = ChartFactory.createBarChart(
				"Bar Chart Demo", "Category", "Value", paramCategoryDataset,
				PlotOrientation.VERTICAL, true, true, false);
		//设置柱状图属性
		localJFreeChart.setBackgroundPaint(Color.white);
		
		//获取柱状图的标注点集合
		CategoryPlot localCategoryPlot = localJFreeChart.getCategoryPlot();
		
		//设置标注点的背景色
		localCategoryPlot.setBackgroundPaint(Color.lightGray);
		
		//设置绘制区域的方格线的颜色
		localCategoryPlot.setDomainGridlinePaint(Color.white);
		//是方格线可见
		localCategoryPlot.setDomainGridlinesVisible(true);
		//设置方格线变动绘制颜色
		localCategoryPlot.setRangeGridlinePaint(Color.white);
		
		//得到数值坐标轴
		NumberAxis localNumberAxis = (NumberAxis) localCategoryPlot
				.getRangeAxis();
		
		//设置坐标轴单元
		localNumberAxis.setStandardTickUnits(NumberAxis
				.createIntegerTickUnits());
		
		//得到柱状图渲染器
		BarRenderer localBarRenderer = (BarRenderer) localCategoryPlot
				.getRenderer();
		
		//如果超出绘制区域边界将不可见
		localBarRenderer.setDrawBarOutline(false);
		
		//创建倾斜度对象
		GradientPaint localGradientPaint1 = new GradientPaint(0.0F, 0.0F,
				Color.blue, 0.0F, 0.0F, new Color(0, 0, 64));
		GradientPaint localGradientPaint2 = new GradientPaint(0.0F, 0.0F,
				Color.green, 0.0F, 0.0F, new Color(0, 64, 0));
		GradientPaint localGradientPaint3 = new GradientPaint(0.0F, 0.0F,
				Color.red, 0.0F, 0.0F, new Color(64, 0, 0));
		
		//为渲染器设置倾斜度
		localBarRenderer.setSeriesPaint(0, localGradientPaint1);
		localBarRenderer.setSeriesPaint(1, localGradientPaint2);
		localBarRenderer.setSeriesPaint(2, localGradientPaint3);
		
		//旋转坐标轴
		CategoryAxis localCategoryAxis = localCategoryPlot.getDomainAxis();
		
		localCategoryAxis.setCategoryLabelPositions(CategoryLabelPositions
				.createUpRotationLabelPositions(0.5235987755982988D));
		
		return localJFreeChart;
	}

	/**
	 * 创建3D柱状图
	 * 
	 * @return
	 */
	public JFreeChart createBarChart3D() {
		// 设置坐标点
		double[][] arrayOfDouble = { { 10.0D, 4.0D, 15.0D, 14.0D },
				{ -5.0D, -7.0D, 14.0D, -3.0D }, { 6.0D, 17.0D, -12.0D, 7.0D },
				{ 7.0D, 15.0D, 11.0D, 0.0D }, { -8.0D, -6.0D, 10.0D, -9.0D },
				{ 9.0D, 8.0D, 0.0D, 6.0D }, { -10.0D, 9.0D, 7.0D, 7.0D },
				{ 11.0D, 13.0D, 9.0D, 9.0D }, { -3.0D, 7.0D, 11.0D, -10.0D } };
		// 创建图表的数据集合,第一个参数:横坐标的文字说明;第二个参数:纵坐标的文字说明;第三个参数:坐标数组
		CategoryDataset paramCategoryDataset = DatasetUtilities
				.createCategoryDataset("Series ", "Category ", arrayOfDouble);
		// 创建3D图表
		JFreeChart localJFreeChart = ChartFactory.createBarChart3D(
				"3D Bar Chart Demo", "Category", "Value", paramCategoryDataset,
				PlotOrientation.VERTICAL, true, true, false);
		// 得到横坐标点集合对象
		CategoryPlot localCategoryPlot = localJFreeChart.getCategoryPlot();
		// 设置方格可见
		localCategoryPlot.setDomainGridlinesVisible(true);
		// 得到坐标轴
		CategoryAxis localCategoryAxis = localCategoryPlot.getDomainAxis();
		// 设置标注点位置
		localCategoryAxis.setCategoryLabelPositions(CategoryLabelPositions
				.createUpRotationLabelPositions(0.3926990816987241D));
		// 创建3D柱状图渲染对象
		BarRenderer3D localBarRenderer3D = (BarRenderer3D) localCategoryPlot
				.getRenderer();
		// 设置超出边界不可见
		localBarRenderer3D.setDrawBarOutline(false);
		// 返回图表对象
		return localJFreeChart;
	}

}

  4.2 绘制饼状图的类的源码

package org.xjh.web.chart;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Point;
import java.awt.RadialGradientPaint;
import java.awt.geom.Point2D;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.ui.HorizontalAlignment;
import org.jfree.ui.RectangleEdge;

/**
 * 饼状图测试
 * @author xjh
 *
 */
public class PieChartTest {

	
	/**
     * Creates a chart.
     *
     * @return A chart.
     */
	public JFreeChart createPieChart() {
		
		//Creates a sample dataset 创建一个简单的数据集
		DefaultPieDataset dataset = new DefaultPieDataset();
		dataset.setValue("Samsung", new Double(27.8));
		dataset.setValue("Others", new Double(55.3));
		dataset.setValue("Nokia", new Double(16.8));
		dataset.setValue("Apple", new Double(17.1));

		//create a chart object  根据饼状图的标题和数据集等参数创建图表对象
		JFreeChart chart = ChartFactory.createPieChart(
				"Smart Phones Manufactured / Q3 2011", // chart title
				dataset, // data
				false, // no legend
				true, // tooltips
				false // no URL generation
				);

		// set a custom background for the chart 为饼状图设置背景色
		chart.setBackgroundPaint(new GradientPaint(new Point(0, 0), new Color(
				20, 20, 20), new Point(400, 200), Color.DARK_GRAY));

		// customise the title position and font  为饼状图的标题设置:位置、颜色、字体
		TextTitle t = chart.getTitle();
		t.setHorizontalAlignment(HorizontalAlignment.LEFT);
		t.setPaint(new Color(240, 240, 240));
		t.setFont(new Font("Arial", Font.BOLD, 26));

		//定义饼图的标绘区域
		PiePlot plot = (PiePlot) chart.getPlot();
		plot.setBackgroundPaint(null);
		plot.setInteriorGap(0.04);
		plot.setOutlineVisible(false);

		// use gradients and white borders for the section colours  为部分颜色加入渐变色和白色边框
		plot.setSectionPaint("Others",
				createGradientPaint(new Color(200, 200, 255), Color.BLUE)); //在每个标绘区域绘制倾斜的内容
		plot.setSectionPaint("Samsung",
				createGradientPaint(new Color(255, 200, 200), Color.RED));
		plot.setSectionPaint("Apple",
				createGradientPaint(new Color(200, 255, 200), Color.GREEN));
		plot.setSectionPaint("Nokia",
				createGradientPaint(new Color(200, 255, 200), Color.YELLOW));
		plot.setBaseSectionOutlinePaint(Color.WHITE);
		plot.setSectionOutlinesVisible(true);
		plot.setBaseSectionOutlineStroke(new BasicStroke(2.0f));

		// customise the section label appearance   为标签定义外观
		plot.setLabelFont(new Font("Courier New", Font.BOLD, 20));
		plot.setLabelLinkPaint(Color.WHITE);
		plot.setLabelLinkStroke(new BasicStroke(2.0f));
		plot.setLabelOutlineStroke(null);
		plot.setLabelPaint(Color.WHITE);
		plot.setLabelBackgroundPaint(null);

		// add a subtitle giving the data source  为每个数据源添加子标题
		TextTitle source = new TextTitle(
				"Source: http://www.bbc.co.uk/news/business-15489523",
				new Font("Courier New", Font.PLAIN, 12));
		source.setPaint(Color.WHITE);
		source.setPosition(RectangleEdge.BOTTOM);
		source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
		chart.addSubtitle(source);
		
		return chart;
	}
	
	/**
     * A utility method for creating gradient paints.
     * 创建径向梯度着色的绘画
     * @param c1  color 1.
     * @param c2  color 2.
     * 
     * @return A radial gradient paint.
     */
    private RadialGradientPaint createGradientPaint(Color c1, Color c2) {
        Point2D center = new Point2D.Float(0, 0);
        float radius = 200;
        float[] dist = {0.0f, 1.0f};
        return new RadialGradientPaint(center, radius, dist,
                new Color[] {c1, c2});
    }

}

  4.3 绘制线型图的类的源码

package org.xjh.web.chart;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.Ellipse2D;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.HorizontalAlignment;
import org.jfree.ui.RectangleEdge;

/**
 * 线状图测试
 * @author xjh
 *
 */
public class LineChartTest {

	public JFreeChart createLineChart() {
		//创建分类数据集
		DefaultCategoryDataset localDefaultCategoryDataset = new DefaultCategoryDataset();
		localDefaultCategoryDataset.addValue(212.0D, "Classes", "JDK 1.0");
		localDefaultCategoryDataset.addValue(504.0D, "Classes", "JDK 1.1");
		localDefaultCategoryDataset.addValue(1520.0D, "Classes", "JDK 1.2");
		localDefaultCategoryDataset.addValue(1842.0D, "Classes", "JDK 1.3");
		localDefaultCategoryDataset.addValue(2991.0D, "Classes", "JDK 1.4");
		localDefaultCategoryDataset.addValue(3500.0D, "Classes", "JDK 1.5");
		
		//创建线状图
		JFreeChart localJFreeChart = ChartFactory.createLineChart("Java Standard Class Library", null, "Class Count", localDefaultCategoryDataset, PlotOrientation.VERTICAL, false, true, false);
	    localJFreeChart.addSubtitle(new TextTitle("Number of Classes By Release"));
	    
	    //设置文本标题
	    TextTitle localTextTitle = new TextTitle("Source: Java In A Nutshell (5th Edition) by David Flanagan (O'Reilly)");
	    localTextTitle.setFont(new Font("SansSerif", 0, 10));
	    localTextTitle.setPosition(RectangleEdge.BOTTOM);
	    localTextTitle.setHorizontalAlignment(HorizontalAlignment.RIGHT);
	    localJFreeChart.addSubtitle(localTextTitle);
	    
	    //分类描绘点
	    CategoryPlot localCategoryPlot = (CategoryPlot)localJFreeChart.getPlot();
	    localCategoryPlot.setRangePannable(true);
	    localCategoryPlot.setRangeGridlinesVisible(false);
	    //设置坐标轴
	    Object localObject = (NumberAxis)localCategoryPlot.getRangeAxis();
	    ((NumberAxis)localObject).setStandardTickUnits(NumberAxis.createIntegerTickUnits());
	    ChartUtilities.applyCurrentTheme(localJFreeChart);
	    
	    //得到图表渲染器
	    LineAndShapeRenderer localLineAndShapeRenderer = (LineAndShapeRenderer)localCategoryPlot.getRenderer();
	    //设置渲染器属性
	    localLineAndShapeRenderer.setBaseShapesVisible(true);
	    localLineAndShapeRenderer.setDrawOutlines(true);
	    localLineAndShapeRenderer.setUseFillPaint(true);
	    localLineAndShapeRenderer.setBaseFillPaint(Color.white);
	    localLineAndShapeRenderer.setSeriesStroke(0, new BasicStroke(3.0F));
	    localLineAndShapeRenderer.setSeriesOutlineStroke(0, new BasicStroke(2.0F));
	    localLineAndShapeRenderer.setSeriesShape(0, new Ellipse2D.Double(-5.0D, -5.0D, 10.0D, 10.0D));
	    
	    return localJFreeChart;
	}

}

  4.4 绘制环形图的类的源码
package org.xjh.web.chart;

import java.awt.Font;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.RingPlot;
import org.jfree.data.general.DefaultPieDataset;

/**
 * 环形图测试
 * @author xjh
 *
 */
public class RingChartTest {

	public JFreeChart createRingChart() {
		//创建数据集对象
		DefaultPieDataset localDefaultPieDataset = new DefaultPieDataset();
	    localDefaultPieDataset.setValue("One", new Double(43.200000000000003D));
	    localDefaultPieDataset.setValue("Two", new Double(10.0D));
	    localDefaultPieDataset.setValue("Three", new Double(27.5D));
	    localDefaultPieDataset.setValue("Four", new Double(17.5D));
	    localDefaultPieDataset.setValue("Five", new Double(11.0D));
	    localDefaultPieDataset.setValue("Six", new Double(19.399999999999999D));
	    
	    //创建环形图
	    JFreeChart localJFreeChart = ChartFactory.createRingChart("Ring Chart Demo 1", localDefaultPieDataset, false, true, false);
	    
	    //获得环形图标注点并设置它的属性
	    RingPlot localRingPlot = (RingPlot)localJFreeChart.getPlot();
	    localRingPlot.setLabelFont(new Font("SansSerif", 0, 12));
	    localRingPlot.setNoDataMessage("No data available");
	    localRingPlot.setSectionDepth(0.35D);
	    localRingPlot.setCircular(false);
	    localRingPlot.setLabelGap(0.02D);
	    
		return localJFreeChart;
	}

}

5. 创建测试页面jfreechartTest.jsp ,源码如下:

<%@ page import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%>


  
    JFreeChart测试
	
  
  
  
    

宽: px 高: px 图形类型:



6.整个测四项目的目录结构如下图所示:
Java绘制图表框架JFreeChart入门_第2张图片


7.测试运行

  7.1 柱状图测试
Java绘制图表框架JFreeChart入门_第3张图片


  7.2 饼状图测试

Java绘制图表框架JFreeChart入门_第4张图片


  7.3 线形图测试

Java绘制图表框架JFreeChart入门_第5张图片


  7.4 环形图测试

Java绘制图表框架JFreeChart入门_第6张图片



结束语:上面的测试代码都来自JFreeChart中的demo,如果想获得更多的测试用例请参看:jfreechart-1.0.17-demo.jar


你可能感兴趣的:(图表,Java,java,jfreechart)