Fix Bar Chart Width and Spacing between bars in JFreeChart

bar-chartjfreechartwidth

I have stacked bar chart in which the number of columns is dynamic, can change from 1 to n columns. I want the spacing between the charts and width of the bar to be consistent. How do I fix it. Please suggest solutions / ideas.

Best Answer

In a Stacked Bar chart, you can change the spacing between bars using

  • CategoryAxis.setLowerMargin
  • CategoryAxis.setMargin and
  • CategoryAxis.setUpperMargin

Code is below

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;
}