Width of the bar in Jfreechart
Asked Answered
C

4

18

Is there a way to adjust the width of the bars in a Barchart?

I create my chart with the following code.

final JFreeChart chart = ChartFactory.createBarChart("Report", // chart title
                "Date", // domain axis label
                "Number", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
                );  
Coniology answered 29/12, 2009 at 10:28 Comment(0)
B
24

You can also set the maximum width of a bar. This is useful if you have a wide chart but occasionally there are only one or two data points and you don't want a single big fat bar taking up the whole area.

CategoryPlot categoryPlot = chart.getCategoryPlot();
BarRenderer br = (BarRenderer) categoryPlot.getRenderer();
br.setMaximumBarWidth(.35); // set maximum width to 35% of chart
Bisexual answered 31/12, 2009 at 14:5 Comment(0)
R
10

You can't directly specify the width of the bars, but there's a few attributes that can be changed which affect the width. You should take a look at the lowerMargin, upperMargin and categoryMargin attributes defined by the CategoryAxis or the itemMargin attribute in the BarRenderer.

For example:

    BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
    renderer.setItemMargin(.1);

The double specified in setItemMargin(double percent) is the percentage of the overall length of the category axis that will be used for the space between the bars within the same category (default is .2 or 20%). The smaller this value is, the larger the bars will be.

Remediosremedy answered 29/12, 2009 at 12:5 Comment(0)
K
9

After getting no results using positive margins and zero, I tried using negative numbers for itemMargin to see what would happen. The bars started getting thicker. I don't know if this is recommended, though, since you will get overlap if there is not enough space available.

BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
renderer.setItemMargin(-2);
Keelson answered 15/6, 2010 at 1:54 Comment(1)
Brilliant. I'm having the same problem again and I couldn't achieve anything with setMaximumBarWidth, this did the trick. Thanks.Southpaw
R
5

According to Dave Gilbert (JFreeChart Project Leader)

The bar widths are automatically calculated and will depend on the chart or plot width and the number of items in your dataset.

See the discussion here.

Radionuclide answered 29/12, 2009 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.