Search code examples
javaswingcolorsjfreechartbar-chart

How can I change the colour of specific bars in jFreeChart bar


I have coded an application which reads a column from a jTable and plots it in a Bar Chart. It works okay, but now, I want to colour some bars of the chart depending on the value it reads from the length column.

Here is a normal example of my application:

Example

And now, as I explained, I want to change the colour of specific bars, for example attending to this rule:

if length is >18 We will colour the bar BLUE

else if length is <=18 We will colour the bar RED


Solution

  • Generate the dataset:

    final double[][] data = new double[][] {{4.0, 3.0, -2.0, 3.0, 6.0}};
    DatasetUtilities.createCategoryDataset("Length", "Day of the Month", data);
    

    Iterate through each point and define its own color when creating the renderer:

    Paint[] colors = new Paint[data.length];
    for (int i = 0; i < colors.length; i++) {
        color[i] = data > 18 ? Color.blue : Color.red;
    }
    final CategoryItemRenderer renderer = new CustomRenderer(colors);
    

    This article can be useful: Different bar chart colours within a series

    Hope it helps.