【问题标题】:Fix Bar Chart Width and Spacing between bars in JFreeChart修复 JFreeChart 中条形图的宽度和间距
【发布时间】:2010-05-11 04:33:15
【问题描述】:

我有堆叠条形图,其中列数是动态的,可以从 1 列更改为 n 列。我希望图表之间的间距和条形的宽度保持一致。我如何解决它。请提出解决方案/想法。

【问题讨论】:

    标签: width jfreechart bar-chart


    【解决方案1】:

    在堆积条形图中,您可以使用

    更改条形之间的间距
    • CategoryAxis.setLowerMargin
    • CategoryAxis.setMargin 和
    • CategoryAxis.setUpperMargin

    代码如下

    protected JFreeChart generateGraph() {
    
      CategoryAxis categoryAxis = new CategoryAxis("Categories");
      categoryAxis.setLowerMargin(.01);
      categoryAxis.setCategoryMargin(.01);
      categoryAxis.setUpperMargin(.01);      
      categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    
      ValueAxis valueAxis = new NumberAxis("Values");
    
      StackedBarRenderer renderer = new StackedBarRenderer();
      renderer.setBarPainter(new StandardBarPainter());
      renderer.setDrawBarOutline(false);
      renderer.setShadowVisible(false);
      renderer.setBaseItemLabelsVisible(true);
      renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    
      CategoryPlot plot = new CategoryPlot( _dataset,
                                            categoryAxis,
                                            valueAxis,
                                            renderer);
    
      plot.setOrientation(PlotOrientation.VERTICAL);
    
      JFreeChart chart = new JFreeChart( "Title",
                              JFreeChart.DEFAULT_TITLE_FONT,
                              plot,
                              true);
      //ChartFactory.getChartTheme().apply(_chart);
      return chart;
    }
    

    【讨论】:

      【解决方案2】:

      StackedBarRenderer 致力于使“[条] 之间的间距和条的宽度保持一致。”随着列数的变化,不清楚你希望它做什么不同。相关几何由父BarRenderercalculateBarWidth() 等方法确定,可以根据需要覆盖。另外,验证每个系列中的每个类别都有一个值。

      【讨论】:

      • 我使用了渲染器的setMaximumBarWidth方法来动态设置宽度。
      • 优秀。我不知道setMaximumBarWidth(),它看起来更容易。我会把它作为一个单独的答案投票。