使用xml文件的简单jfreechart条形图

时间:2014-09-03 18:05:01

标签: java xml jfreechart

我需要根据" state"的值生成一个条形图(如下所示)。 XML文件中的字段。 Y轴上的条形是"键" XML文件中的字段。 (计划A,计划B等)。

这些酒吧的颜色取决于"状态"相应标签中的字段。 (成功 - 绿色,失败 - 红色,InProgress - 蓝色)

我尝试通过读取XML文件来搜索如何生成条形图。但我无法弄清楚。

请帮助我解决解析状态"来自xml文件的字段&这个用例的正确的jfreechart。

xml文件内容:

<results>
<result id="1" number="10" lifeCycleState="Finished" state="Failed" key="PLAN-A">
</result>

<result id="2" number="20" lifeCycleState="Finished" state="Success" key="PLAN-B">
</result>

<result id="3" number="30" lifeCycleState="Finished" state="Success" key="PLAN-C">
</result>

<result id="4" number="40" lifeCycleState="InProgress" state="InProgress" key="PLAN-D">
</result>
</results>

图表是:

enter image description here

2 个答案:

答案 0 :(得分:2)

以下是您要找的内容的一个示例:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
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.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class BarChartDemo extends ApplicationFrame {


    public BarChartDemo(final String title) throws Exception {

        super(title);

        final CategoryDataset dataset = createDataset();
        final JFreeChart chart = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(500, 270));
        setContentPane(chartPanel);

    }

    /**
     * Returns a sample dataset.
     * 
     * @return The dataset.
     * @throws ParserConfigurationException 
     * @throws IOException 
     * @throws SAXException 
     */
    private CategoryDataset createDataset() throws Exception {
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document document = db.parse(new File("src/input.xml"));
         NodeList nodeList = document.getElementsByTagName("result");


         for(int x=nodeList.getLength()-1;x>=0;x--){
             dataset.addValue(10.0, nodeList.item(x).getAttributes().getNamedItem("state").getNodeValue(),nodeList.item(x).getAttributes().getNamedItem("key").getNodeValue());
         }

        return dataset;

    }

    /**
     * Creates a sample chart.
     * 
     * @param dataset  the dataset.
     * 
     * @return The chart.
     */
    private JFreeChart createChart(final CategoryDataset dataset) {

        // create the chart...
        final JFreeChart chart = ChartFactory.createBarChart(
            "Bar Chart Demo",         // chart title
            "key",               // domain axis label
            "number",                  // range axis label
            dataset,                  // data
            PlotOrientation.HORIZONTAL, // orientation
            true,                     // include legend
            true,                     // tooltips?
            false                     // URLs?
        );

        // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

        // set the background color for the chart...
        chart.setBackgroundPaint(Color.white);

        // get a reference to the plot for further customisation...
        final CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);

        // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        // disable bar outlines...
        final BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(false);

        // set up gradient paints for series...
        final GradientPaint gp0 = new GradientPaint(
            0.0f, 0.0f, Color.blue, 
            0.0f, 0.0f, Color.lightGray
        );
        final GradientPaint gp1 = new GradientPaint(
            0.0f, 0.0f, Color.green, 
            0.0f, 0.0f, Color.lightGray
        );
        final GradientPaint gp2 = new GradientPaint(
            0.0f, 0.0f, Color.red, 
            0.0f, 0.0f, Color.lightGray
        );
        renderer.setSeriesPaint(0, gp0);
        renderer.setSeriesPaint(1, gp1);
        renderer.setSeriesPaint(2, gp2);

   final CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(
        CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)
    );

        return chart;

    }


    public static void main(final String[] args) throws Exception {

        final BarChartDemo demo = new BarChartDemo("Barchart");
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);

    }

}

修改:根据状态值修复颜色,请执行以下操作:

 /*   renderer.setSeriesPaint(0, gp0);
    renderer.setSeriesPaint(1, gp1);
    renderer.setSeriesPaint(2, gp2);*/

在您的程序中注释上面的代码,然后添加以下代码:

int pos=0;
   List<Comparable> statusList = dataset.getRowKeys();
   for(Comparable status : statusList){

       if(status.equals("InProgress")){
           renderer.setSeriesPaint(pos,gp0);
       }
       else if (status.equals("Success")){
           renderer.setSeriesPaint(pos,gp1);
       }
       else if (status.equals("Failed")){
           renderer.setSeriesPaint(pos,gp2);
       }
       pos++;
   }

<强> EDIT2: 要在createChart方法中保存为图片,请在执行return chart之前添加您的代码:

        int width=640; 
        int height=480; 
        File BarChart=new File("src/chart.png"); 
        ChartUtilities.saveChartAsPNG(BarChart, chart, width, height);
        return chart;

当您运行该程序时,它将为您提供以下内容: enter image description here

答案 1 :(得分:1)

一个小点,图表显示所有值的10.0。 更改: dataset.addValue(10.0,... 至: dataset.addValue(Double.valueOf(nodeList.item(x).getAttributes()。getNamedItem(&#34; number&#34;)。getNodeValue()),...