美文网首页大学生求职互联网科技码农的世界
[知了堂学员笔记] jfreechart创建简单的柱状图和饼图

[知了堂学员笔记] jfreechart创建简单的柱状图和饼图

作者: b5c1a1cecdbe | 来源:发表于2017-09-25 11:45 被阅读23次

    jfreechart是什么?

    JFreeChart是JAVA平台上的一个开放的图表绘制类库。它完全使用JAVA语言编写,是为applications, applets, servlets 以及JSP等使用所设计。JFreeChart可生
    成饼图(pie charts)、柱状图(bar charts)、散点图(scatter plots)、时序图(time series)、甘特图(Gantt charts)等等多种图表,并且可以产生PNG和JPEG格式的输出
    利用jfreechart创建简单的柱状图和饼图


    柱状图

    图中的样式等都为默认效果,下面是实现的代码

    DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();  
              
            categoryDataset.addValue(110, "四川", "西瓜");  
            categoryDataset.addValue(210, "四川", "苹果");  
            categoryDataset.addValue(310, "四川", "荔枝");  
            categoryDataset.addValue(410, "四川", "香蕉");  
              
            JFreeChart jFreeChart = ChartFactory.createBarChart("水果销量", null, "销售值", categoryDataset);  
              
            setChartByFont(jFreeChart);//解决乱码  
              
            OutputStream os = response.getOutputStream();  
            ChartUtilities.writeChartAsPNG(os, jFreeChart, 500, 300);  
            os.flush();  
            os.close();  
            return null;  
        }  
    
    

    下面为解决乱码的方法setChartByFont()

    private void setChartByFont(JFreeChart jFreeChart) {  
            TextTitle textTitle = jFreeChart.getTitle();  
            textTitle.setFont(new Font("宋体",Font.BOLD,20));//设置标题的字体  
              
            CategoryPlot categoryPlot = jFreeChart.getCategoryPlot();  
              
            CategoryAxis categoryAxis = categoryPlot.getDomainAxis();//x轴对象  
            ValueAxis valueAxis = categoryPlot.getRangeAxis();//y轴对象  
              
            categoryAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12));  
            valueAxis.setLabelFont(new Font("宋体",Font.BOLD,12));  
              
            LegendTitle legendTitle = jFreeChart.getLegend();  
            if(legendTitle != null) {  
                legendTitle.setItemFont(new Font("sans-serif", Font.BOLD, 12));  
            }  
              
        }  
    
    饼图

    效果设置了部分图表的样式

    public String createPieChart_01(HttpServletRequest request,HttpServletResponse response) throws IOException {  
                DefaultPieDataset dataset = new DefaultPieDataset();  
                dataset.setValue("初级程序员", 10000);  
                dataset.setValue("中级程序员", 8000);  
                dataset.setValue("高级程序员", 6000);  
                dataset.setValue("架构师", 2000);  
                dataset.setValue("项目经理", 6000);  
                  
                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));  
                  
                standardChartTheme.setLegendBackgroundPaint(new Color(238,238,224));// 设置标注背景色  
                standardChartTheme.setLegendItemPaint(Color.BLACK);//设置字体颜色  
                //standardChartTheme.setChartBackgroundPaint(new Color(174,238,238));//图表背景色  
                standardChartTheme.setPlotBackgroundPaint(new Color(174,238,238));// 绘制区域  
                standardChartTheme.setPlotOutlinePaint(new Color(174,238,238));// 绘制区域外边框         
                ChartFactory.setChartTheme(standardChartTheme);  
                  
                JFreeChart chart=ChartFactory.createPieChart("IT行业职位分布图",dataset,true,true,false);   
                //第一个参数是标题,第二个参数是一个数据集,第三个参数表示是否显示Legend,第四个参数表示是否显示提示,第五个参数表示图中是否存在URL  
                chart.getLegend().setFrame(new BlockBorder(Color.WHITE));// 设置标注无边框  底部  
                //chart.getLegend().setPosition(RectangleEdge.RIGHT);// 标注位于右侧  
                  
                PiePlot pieplot = (PiePlot) chart.getPlot();    
                pieplot.setLabelFont(new Font("宋体", 0, 15));    
                StandardPieSectionLabelGenerator standarPieIG = new StandardPieSectionLabelGenerator("{0}:({1},{2})", NumberFormat.getNumberInstance(),new DecimalFormat("0%"));    
                pieplot.setLabelGenerator(standarPieIG);    
                pieplot.setLabelOutlinePaint(null);// 去掉边框  
                pieplot.setMaximumLabelWidth(0.2);//边框宽度  
                pieplot.setLabelBackgroundPaint(new Color(180,238,180));//标签底色  
                  
                OutputStream out = response.getOutputStream();  
                response.setContentType("image/jpeg");  
                // out,是一个OutputStream;  
                // chart,是你生成的 JFreeChart 类的对象  
                // 后面两个是图片的大小  
                ChartUtilities.writeChartAsJPEG(out, chart, 600, 500);  
                out.flush();  
                out.close();  
                return null;      
            }  
    
    

    解决乱码的方法上面的相同
    有数值的3D柱状图

    public String createBarChart_04(HttpServletRequest request, HttpServletResponse response) throws IOException {  
            double[][] data = {  
                    {113,232,111,511},  
                    {252,141,512,311},  
                    {614,151,156,166},  
                    {513,514,161,512}};  
            String[] rowKeys = {"西瓜","苹果","荔枝","香蕉"};  
            String[] columnKeys = {"北京","上海","天津","重庆"};  
              
            CategoryDataset categoryDataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);  
            JFreeChart jFreeChart = ChartFactory.createBarChart3D("水果销量", null, "销量值", categoryDataset, PlotOrientation.VERTICAL, true, false, false);  
            setChartByFont(jFreeChart);  
              
            //设置网络背景颜色  
            CategoryPlot categoryPlot = jFreeChart.getCategoryPlot();  
            categoryPlot.setBackgroundPaint(Color.WHITE);  
            //设置网格竖线颜色  
            categoryPlot.setDomainGridlinePaint(Color.PINK);  
            //设置网络横线颜色  
            categoryPlot.setRangeGridlinePaint(Color.PINK);  
            //显示每个柱子的数值  
            BarRenderer3D renderer = new BarRenderer3D();  
            renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());  
            renderer.setBaseItemLabelsVisible(true);  
            //默认情况下柱子的数字是显示在柱子中,所以我们要改变他的显示方向  
            renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));      renderer.setItemLabelAnchorOffset(10D);  
            renderer.setItemLabelAnchorOffset(10D);  
            //设置每个地区包含平行住之间的距离  
            renderer.setItemMargin(0.3);  
            //将渲染对象添加到图形对象中  
            categoryPlot.setRenderer(renderer);  
            //调整X和Y轴之间 对的位置方向  
            categoryPlot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT); //Y轴方向  
            categoryPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); //X轴方向  
              
            jFreeChart.getCategoryPlot().setBackgroundPaint(Color.WHITE);  
            OutputStream os = response.getOutputStream();  
            ChartUtilities.writeChartAsPNG(os, jFreeChart, 500, 300);  
            os.flush();  
            os.close();  
            return null;      
        }  
    

    利用JDBC和数据库链接

    line

    第一步,创建数据库链接

    public final static String USER_NAME = "root";  
        public final static String PASSWORD= "123456";  
        public final static String URL = "jdbc:mysql://localhost:3306/zhiliaotang";  
        public final static String DRIVER = "com.mysql.jdbc.Driver";  
          
        public jfree() {  
            try {  
                Class.forName(DRIVER);  
            } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
            }     
        }  
    

    第二步,将数据库中的数据给图表的数据集

    DefaultPieDataset dpd=new DefaultPieDataset(); //建立一个默认的饼图  
            Connection conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);  
            String sql = "select * from depot";  
            Statement stmt = conn.createStatement();  
            ResultSet rs = stmt.executeQuery(sql);  
            while(rs.next()) {   
                dpd.setValue(rs.getString(2),rs.getInt(3));  
            }  
            conn.close();  
    

    以上为实现的关键代码

    需要注意的地方:

    在创建web项目的时候,jfreechart的jar包需要放在webcontent->WEB-INF->lib目录下,如果只是build path,编译的时候不会报错,但是在启动tomcat的时候会报错

    相关文章

      网友评论

        本文标题:[知了堂学员笔记] jfreechart创建简单的柱状图和饼图

        本文链接:https://www.haomeiwen.com/subject/oeirextx.html