精华内容
下载资源
问答
  • java绘制图表(柱状图、饼图、折线图)包, jfreechart
  • Java绘制图表

    千次阅读 2019-03-26 17:19:43
    /** * 绘制图表工具类 * * @author wangzhongxing * @version $Id: JFreeChartUtil.java, v 0.1 2019年03月25日 8:06 PM wangzhongxing Exp $ */ public class JFreeChartUtil { /** * 绘制条形图,并生成图片 * * ...

    maven引入配置

    <dependency>
        <groupId>jfree</groupId>
        <artifactId>jfreechart</artifactId>
        <version>1.0.13</version>
    </dependency>
    <dependency>
        <groupId>org.jfree</groupId>
        <artifactId>jcommon</artifactId>
        <version>1.0.24</version>
    </dependency>
    <dependency>
        <groupId>incanter</groupId>
        <artifactId>gnujaxp</artifactId>
        <version>1</version>
    </dependency>
    

    工具类

    当中绘制带刻度的雷达图实现方法是参考别人的解决方案,源文档连接:https://blog.51cto.com/wangjierui/116845

    package com.wangzhongxing.springcloud.common.utils;
    
    import com.wangzhongxing.springcloud.common.config.JFreeChartConfig;
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartUtilities;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.title.LegendTitle;
    import org.jfree.chart.title.TextTitle;
    import org.jfree.data.category.DefaultCategoryDataset;
    import org.jfree.data.general.DefaultPieDataset;
    import org.jfree.ui.RectangleEdge;
    
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    
    /**
     * 绘制图表工具类
     *
     * @author wangzhongxing
     * @version $Id: JFreeChartUtil.java, v 0.1 2019年03月25日 8:06 PM wangzhongxing Exp $
     */
    public class JFreeChartUtil {
    
        /**
         * 绘制条形图,并生成图片
         *
         * @param config     图表配置参数
         * @param dataset    图表内容数据
         * @param outputFile 输出图片路径
         * @return
         */
        public static boolean drawBarChart(JFreeChartConfig config, DefaultCategoryDataset dataset,
                                           String outputFile) {
            JFreeChart barChart = ChartFactory.createBarChart(config.getTitle(),
                    config.getCategoryAxisLabel(), config.getValueAxisLabel(), dataset,
                    PlotOrientation.VERTICAL, true, true, false);
            // 设置图表背景图颜色
            if (null != config.getBackgroundColor()) {
                barChart.getPlot().setBackgroundPaint(config.getBackgroundColor());
            }
            // 设置图表边框的颜色
            if (null != config.getOutlineColor()) {
                barChart.getPlot().setOutlinePaint(config.getOutlineColor());
            }
            // 设置图表背景图
            if (null != config.getBackgroundImage()) {
                barChart.getPlot().setBackgroundImage(config.getBackgroundImage());
            }
    
            try {
                ChartUtilities.saveChartAsJPEG(new File(outputFile), barChart, config.getWidth(),
                        config.getHeight());
    
                return true;
            } catch (IOException e) {
                return false;
            }
        }
    
        /**
         * 绘制折线图,并生成图片
         *
         * @param config     图表配置参数
         * @param dataset    图表内容数据
         * @param outputFile 输出图片路径
         * @return
         */
        public static boolean drawLineChart(JFreeChartConfig config, DefaultCategoryDataset dataset,
                                            String outputFile) {
            JFreeChart lineChartObject = ChartFactory.createLineChart(config.getTitle(),
                    config.getCategoryAxisLabel(), config.getValueAxisLabel(), dataset,
                    PlotOrientation.VERTICAL, true, true, false);
            // 设置图表背景图颜色
            if (null != config.getBackgroundColor()) {
                lineChartObject.getPlot().setBackgroundPaint(config.getBackgroundColor());
            }
            // 设置图表边框的颜色
            if (null != config.getOutlineColor()) {
                lineChartObject.getPlot().setOutlinePaint(config.getOutlineColor());
            }
            // 设置图表背景图
            if (null != config.getBackgroundImage()) {
                lineChartObject.getPlot().setBackgroundImage(config.getBackgroundImage());
            }
    
            try {
                ChartUtilities.saveChartAsJPEG(new File(outputFile), lineChartObject, config.getWidth(),
                        config.getHeight());
    
                return true;
            } catch (IOException e) {
                return false;
            }
        }
    
        /**
         * 绘制饼图,并生成图片
         *
         * @param config     图表配置参数
         * @param dataset    图表内容数据
         * @param outputFile 输出图片路径
         * @return
         */
        public static boolean drawPieChart(JFreeChartConfig config, DefaultPieDataset dataset,
                                           String outputFile) {
            JFreeChart pieChar = ChartFactory.createPieChart(config.getTitle(), dataset, true, true,
                    false);
            // 设置图表背景图颜色
            if (null != config.getBackgroundColor()) {
                pieChar.getPlot().setBackgroundPaint(config.getBackgroundColor());
            }
            // 设置图表边框的颜色
            if (null != config.getOutlineColor()) {
                pieChar.getPlot().setOutlinePaint(config.getOutlineColor());
            }
            // 设置图表背景图
            if (null != config.getBackgroundImage()) {
                pieChar.getPlot().setBackgroundImage(config.getBackgroundImage());
            }
    
            try {
                ChartUtilities.saveChartAsJPEG(new File(outputFile), pieChar, config.getWidth(),
                        config.getHeight());
    
                return true;
            } catch (IOException e) {
                return false;
            }
        }
    
        public static boolean drawSpiderChart(JFreeChartConfig config, DefaultCategoryDataset dataset,
                                              String outputFile) {
            MySpiderWebPlot spiderwebPlot = new MySpiderWebPlot(dataset);
            JFreeChart jfreechart = new JFreeChart(config.getTitle(), TextTitle.DEFAULT_FONT, spiderwebPlot, false);
            LegendTitle legendtitle = new LegendTitle(spiderwebPlot);
            legendtitle.setPosition(RectangleEdge.BOTTOM);
            jfreechart.addSubtitle(legendtitle);
    
            try {
                ChartUtilities.saveChartAsJPEG(new File(outputFile), jfreechart, config.getWidth(), config.getHeight());
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return true;
        }
    
        public static void main(String[] args) throws IOException {
            // 绘制条形图
            final String price = "price";
            final String number = "number";
            final String type = "type";
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            dataset.addValue(1.1, "Guitar", price);
            dataset.addValue(5, "Guitar", type);
            dataset.addValue(7, "Guitar", number);
    
            dataset.addValue(0.9, "Piano", price);
            dataset.addValue(3, "Piano", type);
            dataset.addValue(3, "Piano", number);
    
            dataset.addValue(0.6, "Drum", price);
            dataset.addValue(2, "Drum", type);
            dataset.addValue(1, "Drum", number);
    
            dataset.addValue(0.8, "Bass", price);
            dataset.addValue(5, "Bass", type);
            dataset.addValue(6, "Bass", number);
    
            JFreeChartConfig config = new JFreeChartConfig();
            config.setTitle("Instrument");
            config.setCategoryAxisLabel("category");
            config.setValueAxisLabel("value");
            config.setWidth(640);
            config.setHeight(480);
            Color outlineColor = SystemColor.WHITE;
            Color backgroundColor = SystemColor.WHITE;
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream("D:/temp/小狗1.jpg"));
            config.setOutlineColor(outlineColor);
            config.setBackgroundColor(backgroundColor);
            config.setBackgroundImage(bufferedImage);
            String barChartFile = "D:/temp/barChart.jpeg";
            boolean barChartResult = drawBarChart(config, dataset, barChartFile);
            System.out.println(barChartResult);
    
            // 绘制折线图
            DefaultCategoryDataset lineChartDataset = new DefaultCategoryDataset();
            lineChartDataset.addValue(2000, "Fender tele", "1970");
            lineChartDataset.addValue(3000, "Fender tele", "1980");
            lineChartDataset.addValue(5000, "Fender tele", "1990");
            lineChartDataset.addValue(7000, "Fender tele", "2000");
            lineChartDataset.addValue(10000, "Fender tele", "2010");
            lineChartDataset.addValue(11400, "Fender tele", "2018");
    
            JFreeChartConfig lineConfig = new JFreeChartConfig();
            lineConfig.setTitle("乐器");
            lineConfig.setCategoryAxisLabel("价格");
            lineConfig.setValueAxisLabel("金额");
            lineConfig.setWidth(640);
            lineConfig.setHeight(480);
            String lineChartFile = "/temp/lineChart.png";
            boolean lineChartResult = drawLineChart(lineConfig, lineChartDataset, lineChartFile);
            System.out.println(lineChartResult);
    
            // 绘制饼图
            JFreeChartConfig pieConfig = new JFreeChartConfig();
            pieConfig.setTitle("乐器");
            pieConfig.setCategoryAxisLabel("种类");
            pieConfig.setValueAxisLabel("数量");
            pieConfig.setWidth(640);
            pieConfig.setHeight(480);
    
            DefaultPieDataset pieDataset = new DefaultPieDataset();
            pieDataset.setValue("吉他", 40);
            pieDataset.setValue("钢琴", 20);
            pieDataset.setValue("架子鼓", 10);
            pieDataset.setValue("贝斯", 30);
    
            String pieChartFile = "/temp/pieChart.png";
            boolean pieChartResult = drawPieChart(pieConfig, pieDataset, pieChartFile);
            System.out.println(pieChartResult);
    
            // 绘制雷达图
            JFreeChartConfig spiderConfig = new JFreeChartConfig();
            spiderConfig.setTitle("水果产量");
            spiderConfig.setWidth(640);
            spiderConfig.setHeight(480);
            DefaultCategoryDataset spiderDataset = new DefaultCategoryDataset();
            String apple = "apple";
            String banana = "banana";
            spiderDataset.addValue(5, apple, "1月");
            spiderDataset.addValue(6, apple, "2月");
            spiderDataset.addValue(2, apple, "3月");
            spiderDataset.addValue(3, apple, "4月");
            spiderDataset.addValue(7, apple, "5月");
            spiderDataset.addValue(4, apple, "6月");
            spiderDataset.addValue(2, banana, "1月");
            spiderDataset.addValue(5, banana, "2月");
            spiderDataset.addValue(4, banana, "3月");
            spiderDataset.addValue(5, banana, "4月");
            spiderDataset.addValue(8, banana, "5月");
            spiderDataset.addValue(9, banana, "6月");
            boolean spiderChartResult = JFreeChartUtil.drawSpiderChart(spiderConfig, spiderDataset, "/temp/spiderChart.png");
            System.out.println(spiderChartResult);
        }
    
    }
    
    

    依赖模型

    
    import java.awt.*;
    
    /**
     *
     * @author wangzhongxing
     * @version $Id: JFreeChartConfig.java, v 0.1 2019年03月26日 4:32 PM wangzhongxing Exp $
     */
    public class JFreeChartConfig {
    
        /**
         * 图表主题
         */
        private String title;
        /**
         * 图表横坐标标题
         */
        private String categoryAxisLabel;
        /**
         * 图表纵坐标标题
         */
        private String valueAxisLabel;
        /**
         * 图表宽度
         */
        private int    width;
        /**
         * 图表高度
         */
        private int    height;
        /**
         * 图表边框颜色
         */
        private Color  outlineColor;
        /**
         * 背景颜色
         */
        private Color  backgroundColor;
        /**
         * 背景图
         */
        private Image  backgroundImage;
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getCategoryAxisLabel() {
            return categoryAxisLabel;
        }
    
        public void setCategoryAxisLabel(String categoryAxisLabel) {
            this.categoryAxisLabel = categoryAxisLabel;
        }
    
        public String getValueAxisLabel() {
            return valueAxisLabel;
        }
    
        public void setValueAxisLabel(String valueAxisLabel) {
            this.valueAxisLabel = valueAxisLabel;
        }
    
        public int getWidth() {
            return width;
        }
    
        public void setWidth(int width) {
            this.width = width;
        }
    
        public int getHeight() {
            return height;
        }
    
        public void setHeight(int height) {
            this.height = height;
        }
    
        public Color getOutlineColor() {
            return outlineColor;
        }
    
        public void setOutlineColor(Color outlineColor) {
            this.outlineColor = outlineColor;
        }
    
        public Color getBackgroundColor() {
            return backgroundColor;
        }
    
        public void setBackgroundColor(Color backgroundColor) {
            this.backgroundColor = backgroundColor;
        }
    
        public Image getBackgroundImage() {
            return backgroundImage;
        }
    
        public void setBackgroundImage(Image backgroundImage) {
            this.backgroundImage = backgroundImage;
        }
    }
    

    雷达图依赖方法

    该方法是引用别人的,原文连接: https://blog.51cto.com/wangjierui/116845

    package com.wangzhongxing.springcloud.common.utils;
    
    import org.jfree.chart.plot.SpiderWebPlot;
    import org.jfree.data.category.CategoryDataset;
    
    import java.awt.*;
    import java.awt.font.FontRenderContext;
    import java.awt.font.LineMetrics;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    
    
    public class MySpiderWebPlot extends SpiderWebPlot {
        private static final long serialVersionUID = -7763566751166048449L;
        private int ticks = DEFAULT_TICKS;
        private static final int DEFAULT_TICKS = 5;
        private NumberFormat format = NumberFormat.getInstance();
        private static final double PERPENDICULAR = 90;
        private static final double TICK_SCALE = 0.015;
        private int valueLabelGap = DEFAULT_GAP;
        private static final int DEFAULT_GAP = 10;
        private static final double THRESHOLD = 15;
    
        MySpiderWebPlot(CategoryDataset createCategoryDataset) {
            super(createCategoryDataset);
        }
    
        @Override
        protected void drawLabel(final Graphics2D g2, final Rectangle2D plotArea, final double value,
                                 final int cat, final double startAngle, final double extent) {
            super.drawLabel(g2, plotArea, value, cat, startAngle, extent);
            final FontRenderContext frc = g2.getFontRenderContext();
            final double[] transformed = new double[2];
            final double[] transformer = new double[2];
            final Arc2D arc1 = new Arc2D.Double(plotArea, startAngle, 0, Arc2D.OPEN);
    
            for (int i = 1; i <= ticks; i++) {
    
                final Point2D point1 = arc1.getEndPoint();
    
                final double deltaX = plotArea.getCenterX();
                final double deltaY = plotArea.getCenterY();
                double labelX = point1.getX() - deltaX;
                double labelY = point1.getY() - deltaY;
    
                final double scale = ((double) i / (double) ticks);
                final AffineTransform tx = AffineTransform.getScaleInstance(scale, scale);
                final AffineTransform pointTrans = AffineTransform.getScaleInstance(scale + TICK_SCALE, scale + TICK_SCALE);
                transformer[0] = labelX;
                transformer[1] = labelY;
                pointTrans.transform(transformer, 0, transformed, 0, 1);
                final double pointX = transformed[0] + deltaX;
                final double pointY = transformed[1] + deltaY;
                tx.transform(transformer, 0, transformed, 0, 1);
                labelX = transformed[0] + deltaX;
                labelY = transformed[1] + deltaY;
    
    
                double rotated = (PERPENDICULAR);
    
                AffineTransform rotateTrans = AffineTransform.getRotateInstance(Math.toRadians(rotated), labelX, labelY);
                transformer[0] = pointX;
                transformer[1] = pointY;
                rotateTrans.transform(transformer, 0, transformed, 0, 1);
                final double x1 = transformed[0];
                final double y1 = transformed[1];
    
                rotated = (-PERPENDICULAR);
                rotateTrans = AffineTransform.getRotateInstance(Math.toRadians(rotated), labelX, labelY);
    
                rotateTrans.transform(transformer, 0, transformed, 0, 1);
    
                final Composite saveComposite = g2.getComposite();
                g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    
                g2.draw(new Line2D.Double(transformed[0], transformed[1], x1, y1));
    
                if (startAngle == this.getStartAngle()) {
                    final String label = format.format(((double) i / (double) ticks) * this.getMaxValue());
                    final Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc);
    
    
                    final LineMetrics lm = getLabelFont().getLineMetrics(label, frc);
                    final double ascent = lm.getAscent();
                    if (Math.abs(labelX - plotArea.getCenterX()) < THRESHOLD) {
                        labelX += valueLabelGap;
                        labelY += ascent / (float) 2;
                    } else if (Math.abs(labelY - plotArea.getCenterY()) < THRESHOLD) {
                        labelY += valueLabelGap;
                    } else if (labelX >= plotArea.getCenterX()) {
                        if (labelY < plotArea.getCenterY()) {
                            labelX += valueLabelGap;
                            labelY += valueLabelGap;
                        } else {
                            labelX -= valueLabelGap;
                            labelY += valueLabelGap;
                        }
                    } else {
                        if (labelY > plotArea.getCenterY()) {
                            labelX -= valueLabelGap;
                            labelY -= valueLabelGap;
                        } else {
                            labelX += valueLabelGap;
                            labelY -= valueLabelGap;
                        }
                    }
                    g2.setPaint(getLabelPaint());
                    g2.setFont(getLabelFont());
                    g2.drawString(label, (float) labelX, (float) labelY);
                }
                g2.setComposite(saveComposite);
            }
        }
    }
    

    生成图片样例

    柱状图

    在这里插入图片描述

    折线图

    在这里插入图片描述

    饼图

    在这里插入图片描述

    雷达图

    在这里插入图片描述

    展开全文
  • Java绘制图表(柱状图、饼图):开放的图表绘制类库JfreeChart(Servlet篇)操作步骤:实例1:BarChart(柱状图)实例2:PieChart(饼图) 操作步骤: 1、新建Dynamic Web项目。 2、导入JFreeChart所需的jar包。 ...

    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.csdn.net/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与数据集的封装只是为了分类方便,四者可以两两组合,烦请自行组合。另外,图中数据纯属虚构,不代表任何实际意义。谢谢理解!如有问题欢迎指出!

    展开全文
  • import java.awt.*;public class ChartFormatTest{public static void main(String args[]){View m_view = new View();RangeRef newRange = null;try {m_view.getLock();//标题 setTextAsValue(行,...

    import com.jxcell.*;

    import java.awt.*;

    public class ChartFormatTest

    {

    public static void main(String args[])

    {

    View m_view = new View();

    RangeRef newRange = null;

    try {

    m_view.getLock();

    //标题 setTextAsValue(行,列,值);

    m_view.setTextAsValue(1,2,"Jan");

    m_view.setTextAsValue(1,3,"Feb");

    m_view.setTextAsValue(1,4,"Mar");

    m_view.setTextAsValue(1,5,"Apr");

    //分项

    m_view.setTextAsValue(2,1,"香蕉");

    m_view.setTextAsValue(3,1,"大鸭梨");

    m_view.setTextAsValue(4,1,"芒果");

    m_view.setTextAsValue(5,1,"水果1");

    m_view.setTextAsValue(6,1,"水果2");

    m_view.setTextAsValue(7,1,"共计");

    //

    m_view.setTextAsValue(1,6,"time");

    m_view.setNumber(2,6,1);

    m_view.setNumber(3,6,2);

    m_view.setNumber(4,6,3);

    m_view.setNumber(5,6,4);

    m_view.setNumber(6,6,5);

    m_view.setNumber(7,6,6);

    //数据区域随机赋值

    for(int col = 2; col <= 5; col++)

    for(int row = 2; row <= 7; row++)

    m_view.setFormula(row, col, "rand()");//rand()为excle随机函数

    //设置公式

    m_view.setFormula(7, 2, "SUM(C3:C7)");

    //选中单元格区域

    m_view.setSelection("C8:F8");

    //编辑复制 向右复制

    m_view.editCopyRight();

    //绘图区坐标addChart(左上列x,左上行y,右下列x,右下行y)

    ChartShape chart = m_view.addChart(0, 9.1, 7, 20.4);

    //图标形式

    chart.setChartType(ChartShape.TypeLine);

    /* TypeBar:横向柱状图 TypePie:饼状图 TypeLine:线状图 TypeArea:面积图 TypeDoughnut:圈图 TypeScatter:线点图 TypeBubble:没怎么看懂,就是一个灰图,不过查阅资料,貌似是泡状图 */

    //设置连接区域

    chart.setLinkRange("Sheet1!$C$2", false);

    //添加一个系列

    chart.addSeries();

    //系列名字

    chart.setSeriesName(0, "Sheet1!$C$2");

    //系列值

    chart.setSeriesYValueFormula(0, "Sheet1!$C$3:$C$7");

    //系列分类

    chart.setCategoryFormula("Sheet1!$B$3:$B$7");

    chart.addSeries();

    chart.setSeriesName(1, "Sheet1!$D$2");

    chart.setSeriesYValueFormula(1, "Sheet1!$D$3:$D$7");

    chart.addSeries();

    chart.setSeriesName(2, "Sheet1!$E$2");

    chart.setSeriesYValueFormula(2, "Sheet1!$E$3:$E$7");

    chart.addSeries();

    chart.setSeriesName(3, "Sheet1!$F$2");

    chart.setSeriesYValueFormula(3, "Sheet1!$F$3:$F$7");

    // chart.getChart().validateData();

    //设置横坐标标题

    chart.setAxisTitle(ChartShape.XAxis, 0, "横坐标标题");

    //设置纵坐标标题

    chart.setAxisTitle(ChartShape.YAxis, 0, "纵坐标标题");

    //设置图表样式

    ChartFormat cf = chart.getChartFormat();

    //设置背景色

    cf.setPattern((short)1);

    cf.setPatternFG(Color.LIGHT_GRAY.getRGB());

    chart.setChartFormat(cf);

    //设置绘图区颜色

    cf = chart.getPlotFormat();

    cf.setPattern((short)1);

    cf.setPatternFG(new Color(204, 255, 255).getRGB());

    chart.setPlotFormat(cf);

    //设置横坐标文字大小

    cf = chart.getAxisFormat(ChartShape.XAxis, 0);

    cf.setFontSizeInPoints(8.5);

    chart.setAxisFormat(ChartShape.XAxis, 0, cf);

    //设置纵坐标文字大小

    cf = chart.getAxisFormat(ChartShape.YAxis, 0);

    cf.setFontSizeInPoints(8.5);

    chart.setAxisFormat(ChartShape.YAxis, 0, cf);

    //设置图标内标线样式

    cf = chart.getSeriesFormat(0);//地0个

    cf.setLineStyle((short)1);

    cf.setLineWeight(3*20);

    cf.setLineColor((new Color(0, 0, 128)).getRGB());

    cf.setMarkerAuto(false);

    cf.setMarkerStyle((short)0);

    chart.setSeriesFormat(0, cf);

    cf = chart.getSeriesFormat(1);

    cf.setLineStyle((short)1);

    cf.setLineWeight(3*20);

    cf.setLineColor((new Color(255, 0, 255)).getRGB());

    cf.setMarkerAuto(false);

    cf.setMarkerStyle((short)0);

    chart.setSeriesFormat(1, cf);

    cf = chart.getSeriesFormat(2);

    cf.setLineStyle((short)1);

    cf.setLineWeight(3*20);

    cf.setLineColor((new Color(255, 255, 0)).getRGB());

    cf.setMarkerAuto(false);

    cf.setMarkerStyle((short)0);

    chart.setSeriesFormat(2, cf);

    cf = chart.getSeriesFormat(3);

    cf.setLineStyle((short)1);

    cf.setLineWeight(3*20);

    cf.setLineColor((new Color(0, 255, 255)).getRGB());

    cf.setMarkerAuto(false);

    cf.setMarkerStyle((short)0);

    chart.setSeriesFormat(3, cf);

    //主格网

    cf = chart.getMajorGridFormat(ChartShape.YAxis, 0);

    cf.setLineStyle((short)2);

    cf.setLineColor((new Color(255, 0, 0)).getRGB());

    cf.setLineAuto();

    chart.setMajorGridFormat(ChartShape.YAxis, 0, cf);

    //图利位置

    chart.setLegendPosition(ChartFormat.LegendPlacementRight);

    //图利样式

    cf = chart.getLegendFormat();

    cf.setFontBold(true);

    cf.setFontSizeInPoints(8);

    chart.setLegendFormat(cf);

    //excel写出路径

    m_view.write("c:\\out.xls");

    System.out.println("end");

    }

    catch (Exception e) {

    System.out.println(e.getMessage());

    }

    finally

    {

    m_view.releaseLock();

    }

    }

    }

    展开全文
  • Java绘制图表框架JFreeChart入门

    千次阅读 2014-04-29 19:16:00
    3.创建处理绘制图表请求的servlet:JFreeChartServlet ,源码如下: package org.xjh.jfreechart; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet....

    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包,如下图所示:



    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"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>JFreeChart测试</title>
    	<style type="text/css">
    		.selectArea span{
    			margin-left:20px;
    			font-size:14px;
    		}
    	</style>
      </head>
      
      <body>
        <p class="selectArea">
        	<span>
    	  		宽:<input type="text" name="chartWidth" id="chartWidthId" value="500"> px
    	    </span>
    		<span> 
    			高:<input type="text" name="chartHeight" id="chartHeightId" value="300"> px
    		</span>
    		<span>
    			图形类型:
    			<select οnchange="getChart(this)">  
    				<option value="-1" selected="selected" >请选择</option>  
    				<option value="bar">柱状图</option>  
    				<option value="pie">饼状图</option>  
    				<option value="line">线形图</option>  
    				<option value="ring">环形图</option>  
    			</select>
    		</span>  
    	</p>
    	<hr/>  
    	<div id="chartDisplayArea">   
    	</div>      
      
      	<script type="text/javascript">
      		
      		//请求图表的方法
    		function getChart(chartType){  
      			
    		    var chartType = chartType.options[chartType.selectedIndex].value;  
    		    
      			if(chartType == "-1"){
      				return ;
      			}
    		    
    		    var width = document.getElementById("chartWidthId").value;  
    		    
    		    var height = document.getElementById("chartHeightId").value; 
    		    
    		    var day = new Date();  
    		    
    		    var newSrc = "${pageContext.request.contextPath}/servlet/JFreeChartServlet.do?chartType=" + chartType + 
    		    				"&width=" + width + "&height=" + height + "&temp=" + day;   
    		    
    		    document.getElementById("chartDisplayArea").innerHTML="<img src='" + newSrc + "'>";  
    		}  
      		
    	</script>  
    	
      </body>
    </html>
    

    6.整个测四项目的目录结构如下图所示:



    7.测试运行

      7.1 柱状图测试


      7.2 饼状图测试


      7.3 线形图测试


      7.4 环形图测试



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


    展开全文
  • 这里写目录标题JFreeChart1)创建JfreeChartDemo...JFreeChart是JAVA平台上的一个开放的图表绘制类库。它完全使用JAVA语言编写,是为applications, applets, servlets 以及JSP等使用所设计。JFreeChart可生成饼图(p
  • 1.java使用poi生成excel插入图表曲线 2.demo包含完成jar包 3.主要用途是过滤数据自动生成曲线图
  • 前言 这个项目是公司有新的需求,...这里包含了使用java绘制word里面的 普通柱状图,堆叠柱状图,簇状柱状图,饼状图,散点图,折线图 其中柱状图和散点图加入了自定义颜色的功能 项目是jdk8+maven+lombok构建 代
  • JAVA写的一个单词统计程序,可统计任意文件的单词出现频率并绘制图表
  • java生成excel图表

    2014-08-19 20:39:48
    java生成excel图表
  • Java Web动态图表编程

    2018-12-30 15:52:17
    Java Web动态图表编程
  • 既然是图表控件,就上 github 一番搜索,关键字 chart,按照 java 一筛选,再按照 start 数量排序,由高到低。基本上 start 从高到低的图表控件就是 MPAndroidChart、hellocharts-android、WilliamChart、XCL-Charts...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 14,749
精华内容 5,899
关键字:

java绘制图表

java 订阅