JFreeChart入门与实践

    JFreeChart是一个开源的JAVA项目,它主要用来开发各种各样的图表,如饼图、柱状图、线图等.

官方网站:http://www.jfree.org/jfreechart/index.html

所需开发包:jfreechart-1.0.9.jar、jcommon-1.0.12.jar、(gnujaxp.jar可不需要)

 

核心类及接口说明:

 

JfreeChart:整个图表的定制,可通过工厂类ChartFactory获得具体的JfreeChart

A chart class implemented using the Java 2D APIs. The current version supports bar charts, line charts, pie charts and xy plots (including time series data).

JFreeChart coordinates several objects to achieve its aim of being able to draw a chart on a Java 2D graphics device: a list of Title objects (which often includes the chart's legend), a Plot and a Dataset (the plot in turn manages a domain axis and a range axis).

DataSet:图表所需要的数据集合

The base interface for data sets.

All datasets are required to support the DatasetChangeEvent mechanism by allowing listeners to register and receive notification of any changes to the dataset.

In addition, all datasets must belong to one (and only one) DatasetGroup. The group object maintains a reader-writer lock which provides synchronised access to the datasets in multi-threaded code.

Plot:根据不同数据指定不同的区域,主要用于显示数据的区域范围

The base class for all plots in JFreeChart. The JFreeChart class delegates the drawing of axes and data to the plot. This base class provides facilities common to most plot types.

Axis:坐标轴

The base class for all axes in JFreeChart. Subclasses are divided into those that display values (ValueAxis) and those that display categories (CategoryAxis).

AbstractRenderer:绘制功能

Base class providing common services for renderers. Most methods that update attributes of the renderer will fire a RendererChangeEvent, which normally means the plot that owns the renderer will receive notification that the renderer has been changed (the plot will, in turn, notify the chart) 

 

实例制作(可以分离的2D饼图,具有提示跟超联接功能的3D饼图,柱状图的制作):

 

饼图制作(2D饼图,3D饼图的制作)

 

1.web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app> 
 
  <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>/servlet/DisplayChart</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2.index.jsp

<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="org.jfree.data.general.DefaultPieDataset"%>
<%@ page import="org.jfree.chart.*"%>
<%@ page import="org.jfree.chart.plot.*"%>
<%@ page import="org.jfree.chart.servlet.ServletUtilities"%>
<%@ page import="org.jfree.chart.labels.StandardPieToolTipGenerator"%>
<%@ page import="org.jfree.chart.urls.StandardPieURLGenerator"%>
<%@ page import="org.jfree.chart.entity.StandardEntityCollection"%>
<%@ page import="java.io.*"%>
<%@ page import="org.jfree.util.Rotation" %>
<%@ page import="org.jfree.chart.labels.StandardPieSectionLabelGenerator" %>
<%@ page import="java.text.NumberFormat" %>
<HTML>
<HEAD>
<META http-equiv=Content-Type content="text/html; charset=GBK">
<META NAME="Author" CONTENT="Alpha">
<TITLE>软件行业资格分配数据图</TITLE>
</HEAD>
<BODY>
<%//去掉[1]~[7]的注释,恢复@部分注释就由2D饼图变为3D饼图
  DefaultPieDataset dataset = new DefaultPieDataset();
  dataset.setValue("软件工程师", 0.40);
  dataset.setValue("高级软件工程师", 0.25);
  dataset.setValue("项目经理", 0.08);
  dataset.setValue("系统分析师", 0.1);
  dataset.setValue("软件架构师", 0.1);
  dataset.setValue("其他", 0.2);
  //@JFreeChart chart = ChartFactory.createPieChart3D("IT行业职业分布图", dataset, true, true, true);
  JFreeChart chart = ChartFactory.createPieChart("IT行业职业分布图", dataset, true, true, true);//[1]
  chart.setBackgroundPaint(java.awt.Color.white);
  //@PiePlot3D pieplot = new PiePlot3D(dataset);//生成一个3D饼图
  PiePlot pieplot = (PiePlot) chart.getPlot();//[2]生成一个2D饼图
  pieplot.setLabelFont(new java.awt.Font("宋体", 0, 12));
  //没有数据的时候显示的内容
  pieplot.setNoDataMessage("no data!");
  //A flag indicating whether the pie chart is circular, or stretched into an elliptical shape
  //设置饼图是圆的(true),还是椭圆的(false);默认为true
  pieplot.setCircular(true);
  //Sets the gap between the edge of the pie and the labels
  //(expressed as a percentage of the plot width) and sends a PlotChangeEvent to
  //all registered listeners
  pieplot.setLabelGap(0.5D);
  //设置开始角度
  pieplot.setStartAngle(150D);
  //设置方向为顺时针方向
  pieplot.setDirection(Rotation.CLOCKWISE);
  //设置透明度,0.5F为半透明,1为不透明,0为全透明
  pieplot.setForegroundAlpha(0.5F);
  //扇区分离显示
  //Sets the amount that a pie section should be exploded and
  //sends a PlotChangeEvent to all registered listeners.
  pieplot.setExplodePercent("高级软件工程师", 0.20000000000000001D);
  pieplot.setExplodePercent(dataset.getKey(1),0.25d);
  void setExplodePercent(int section,double percent) 抽取的那块(1维数据表的分类下标)以及抽取出来的距离(0.0~1.0)
  pieplot.setExplodePercent(1,1.0);
  //{0}选项,{1}数值,{2}百分比
  pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{1}({2})"));//[3]
  pieplot.setLabelBackgroundPaint(java.awt.Color.white);//[4]
  //pieplot.setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("Tooltip for legend item {0}"));//[5]
  pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2})", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));
  //Sets the flag that controls whether simple or extended labels are displayed on the plot,
  //and sends a PlotChangeEvent to all registered listeners.
  pieplot.setSimpleLabels(true);//[6]simple
  //Sets the interior gap and sends a PlotChangeEvent to all registered listeners.
  pieplot.setInteriorGap(0.0D);//[7]
  //设置扇区边框不可见  
  pieplot.setSectionOutlinesVisible(false); 
  //StandardPieURLGenerator(java.lang.String prefix, java.lang.String categoryParameterName, java.lang.String indexParameterName);
  pieplot.setURLGenerator(new StandardPieURLGenerator("index.jsp"));//设定图片链接
  //public StandardPieToolTipGenerator(java.lang.String labelFormat)//"{0}: ({1}, {2})"
  //@pieplot.setToolTipGenerator(new StandardPieToolTipGenerator());
  ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
  //String filename = ServletUtilities.saveChartAsJPEG(chart,500,300,info,session);
  //saveChartAsJPEG可能影响显示
  String filename = ServletUtilities.saveChartAsPNG(chart,500,300,info,session);
  ChartUtilities.writeImageMap(response.getWriter(),"map0",info,true); //new PrintWriter(out);
  String graphURL = request.getContextPath()+"/servlet/DisplayChart?filename=" + filename;
%>

<P ALIGN="CENTER">
<img src="<%= graphURL %>" width=500 height=300 border=0 usemap="#map0" alt="pic">
</P>
</BODY>
</HTML>


柱状图制作:

 

import java.awt.Color;
import java.io.FileOutputStream;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
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.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

public class BarChar {

 private static CategoryDataset createDataset() {
  String s = "First";
  String s1 = "Second";
  String s2 = "Third";
  String s3 = "Category 1";
  String s4 = "Category 2";
  String s5 = "Category 3";
  String s6 = "Category 4";
  String s7 = "Category 5";
  DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
  defaultcategorydataset.addValue(1.0D, s, s3);
  defaultcategorydataset.addValue(4D, s, s4);
  defaultcategorydataset.addValue(3D, s, s5);
  defaultcategorydataset.addValue(5D, s, s6);
  defaultcategorydataset.addValue(5D, s, s7);
  defaultcategorydataset.addValue(5D, s1, s3);
  defaultcategorydataset.addValue(7D, s1, s4);
  defaultcategorydataset.addValue(6D, s1, s5);
  defaultcategorydataset.addValue(8D, s1, s6);
  defaultcategorydataset.addValue(4D, s1, s7);
  defaultcategorydataset.addValue(4D, s2, s3);
  defaultcategorydataset.addValue(3D, s2, s4);
  defaultcategorydataset.addValue(2D, s2, s5);
  defaultcategorydataset.addValue(3D, s2, s6);
  defaultcategorydataset.addValue(6D, s2, s7);
  return defaultcategorydataset;
 }

 private static JFreeChart createChart(CategoryDataset categorydataset) {

 //createBarChart参数说明
  //createBarChart(java.lang.String title, java.lang.String categoryAxisLabel,
  //java.lang.String valueAxisLabel, CategoryDataset dataset,
  //PlotOrientation orientation,boolean legend, boolean tooltips, boolean urls)
  // 图表标题
  // 类型轴的显示标签
  // 数值轴的显示标签
  // 数据集
  // 图表方向:水平、垂直
  // 是否显示图例(类型说明图标)
  // 是否生成工具提示
  // 是否生成URL链接
  JFreeChart jfreechart = ChartFactory.createBarChart("Bar Chart",
    "Category", "Value", categorydataset, PlotOrientation.VERTICAL,
    true, true, false);
  jfreechart.setBackgroundPaint(Color.white);//图片背景白色
  CategoryPlot categoryplot = (CategoryPlot) jfreechart.getPlot();
     categoryplot.setBackgroundPaint(Color.lightGray);//类别轴背景色亮灰色
  categoryplot.setRangeGridlinePaint(Color.white);//横轴方向格线
  NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
  numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
  numberaxis.setUpperMargin(0.14999999999999999D);//设置当前最高柱状图项距离顶部的距离为其自高的百分比
  CategoryItemRenderer categoryitemrenderer = categoryplot.getRenderer();
  categoryitemrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
  categoryitemrenderer.setSeriesItemLabelsVisible(1, Boolean.TRUE);//显示第2类(Category)系列柱形图所对应的Lable
  CategoryAxis categoryaxis = categoryplot.getDomainAxis();
  categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);//设置类别轴上的刻度标签显示位置倾斜45度
  return jfreechart;
 }

 public static void main(String args[]) {
  JFreeChart jfreechart = createChart(createDataset());
  ChartFrame pieFrame = new ChartFrame("Bar Chart Frame",jfreechart);
     pieFrame.pack();
     pieFrame.setVisible(true);
//  try {
//   ChartUtilities.writeChartAsJPEG(new FileOutputStream("d:\\barTest.jpg"), jfreechart, 800, 500);
//  } catch (Exception e) {
//   // TODO Auto-generated catch block
//   e.printStackTrace();
//  }
 }
}

<转自:http://blog.sina.com.cn/s/blog_5ccfe6ad0100biax.html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值