首页 > 解决方案 > 如何在 JFreeChart 中显示 Y 轴为 0 的条形图?

问题描述

我有一个从JFreeChart生成的聚集条形图。我观察到,只有 Y 轴值大于 0 时才会出现条形。我还需要显示 Y 轴值也为 0 的条形。

我在谷歌搜索了很多次,但我找不到解决方案。

感谢您能帮助我做到这一点。

在此处输入图像描述

我的代码:

public static void generateBarChart() throws IOException, ParseException {

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset( );

        dataset.addValue( 0 , "Failed" , "Spec 1" );
        dataset.addValue( 3 , "Passed" , "Spec 1" );
        dataset.addValue( 0 , "Skipped" , "Spec 1" );

        dataset.addValue( 2 , "Failed" , "Spec 2" );
        dataset.addValue( 0 , "Passed" , "Spec 2" );
        dataset.addValue( 1 , "Skipped" , "Spec 2" );

    JFreeChart barChart = ChartFactory.createBarChart(
            "Bar Chart",
            "Count", "Spec Name",
            dataset,PlotOrientation.HORIZONTAL,
            true, true, false);

    CategoryPlot plot = barChart.getCategoryPlot();
    plot.getRangeAxis().setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    plot.getRenderer().setSeriesPaint(0, Color.RED);
    plot.getRenderer().setSeriesPaint(1, Color.GREEN);
    plot.getRenderer().setSeriesPaint(2, Color.BLUE);

    ChartPanel chartPanel = new ChartPanel(barChart, false);

    chartPanel.setBackground( Color.WHITE );
    barChart.getPlot().setBackgroundPaint( Color.GRAY );
    barChart.setBorderVisible(true);
    barChart.setBorderPaint(Color.BLACK);
    ((AbstractRenderer) plot.getRenderer()).setBaseLegendShape(new Rectangle(20,20));
    LegendTitle legend = barChart.getLegend();
    Font labelFont = new Font("SansSerif", Font.TYPE1_FONT, 14);
    legend.setItemFont(labelFont);

    Font categoryAxisFont = new Font("SansSerif", Font.TYPE1_FONT, 14);
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setTickLabelFont(categoryAxisFont);
    categoryAxis.setLabelFont(new Font("Dialog", Font.TRUETYPE_FONT, 14));

    Font rangeAxisFont = new Font("SansSerif", Font.TYPE1_FONT, 16);
    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setTickLabelFont(rangeAxisFont);
    rangeAxis.setLabelFont(new Font("Dialog", Font.TRUETYPE_FONT, 14));

    // Value on the bars
    plot.getRenderer().setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    plot.getRenderer().setBaseItemLabelsVisible(true);
    plot.getRenderer().setItemLabelFont(new Font("Dialog",Font.BOLD,12));
    ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.INSIDE12,
            TextAnchor.TOP_CENTER);
    plot.getRenderer().setBasePositiveItemLabelPosition(position);

    int width = 600;
    int height = 800;

    // Save it, if the pi-chart directory is not there create it
    File directory = new File("./barchart");
    if (! directory.exists()){
        directory.mkdirs();
    }

    File BarChart = new File( "./barchart/barchart.PNG" );
    ChartUtilities.saveChartAsPNG( BarChart , barChart , width , height );
}

谢谢你。

标签: javachartsbar-chartjfreechart

解决方案


推荐阅读