3
votes

I'm making an application that takes some data and it needs to make a bar chart, but the color of a bar MUST be related to data that it is representing.

Imagine that I have this kind of data: BANANA 430 WATER MELLON 300

Now I should make a bar chart, and I would like to paint the BANANA bar with yellow paint, and WATER MELLON bar with green paint. I'm using JFreeChart library in java. My research led me to making my custom renderer, but then if I make custom renderer the colors will appear randomly on bars. Any solution for this?

2
do you extend from AbstractRenderer or subclass of it for your CustomRenderer? - peshkira
@peshkira I just found this piece of code, it just might work, I'll give it a try <!-- language: lang-java --> Plot plot = bar.getPlot(); BarRenderer barRenderer = (BarRenderer)plot.getRenderer(); barRenderer.setSeriesPaint(0, Color.gray); - Drag0
yep, that is what I had in mind. You can also make use of GradientPaint if you want to style them better. good luck! - peshkira
@peshkira I have a problem now again So I add many values to the dataset. Just like this: dataset.addValue(SOME_INTEGER, "series1", ""); dataset.addValue(SOME_INTEGER2, "series2", ""); How can I find out now for which I am setting the color with setSeriesPaint() method? setSeriesPaint() takes in 2 parameters, first one is integer which marks which series I am reffering to.. for example: renderer.setSeriesPaint(series, paint); series parameter is integer here.. and I don't know how to get that integer if I only have String name of series.. - Drag0
in your example: renderer.setSeriesPaint(0, paint) will change the color of "series1" and renderer.setSeriesPaint(1, paint) will change the color of "series2". Basically it depending on the order in which you introduce the series. - peshkira

2 Answers

4
votes

Maybe this http://www.java2s.com/Code/Java/Chart/JFreeChartBarChartDemo3differentcolorswithinaseries.htm can be of help.

See how the code below is used:

    final CategoryItemRenderer renderer = new CustomRenderer(
        new Paint[] {Color.red, Color.blue, Color.green,
            Color.yellow, Color.orange, Color.cyan,
            Color.magenta, Color.blue}
    );
2
votes

Here is a demo, where you can see how to do this. As in the comment above, you have to add the paints to the series as you introduced them (0 is the first, 1 is the second and so on).