4

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.

SKR
  • 779
  • 4
  • 17
  • 31

2 Answers2

5

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;
}
Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
Bernardo
  • 51
  • 1
  • 1
2

StackedBarRenderer devotes some effort to making the "spacing between the [bars] and width of the bar to be consistent." It's not clear what you want it to do differently as the number of columns changes. The relevant geometry is determined by the parent BarRenderer in such methods as calculateBarWidth(), which can be overridden as desired. Also, verify that there is a value for each category in each series.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    I used setMaximumBarWidth method of renderer to set the width dynamically. – SKR May 20 '10 at 03:10
  • Excellent. I wasn't aware of `setMaximumBarWidth()`, and it looks much easier. I'd up-vote it as a separate answer. – trashgod May 20 '10 at 05:13