0

I am trying to plot a dynamic pie chart using JFreeChart. I do not know how many sections will be present in advance. I receive data every second which updates the graph.

How can I set colour for each section of the chart ? I do not wish to have the default colours.

I have tried setting the DrawingSupplier. Doesn't work. Can anybody help ?

chrisrhyno2003
  • 3,906
  • 8
  • 53
  • 102
  • 1
    What's wrong with the `DefaultDrawingSupplier`? Two examples are cited [here](http://stackoverflow.com/a/16754801/230513). – trashgod Jun 27 '15 at 02:03

1 Answers1

1

The Plot of the chart for pie charts can be cast to a PiePlot which lets you set the paint color, outline color, shadow color ect.. of each piece of the pie. Heres a little sample of setting the colors for each piece of the pie. If the number of pieces is greater than the amount of colors defined in our array then it will reuse the colors.

The setSectionPaint method takes any type of java.awt.Paint so you can also pass in gradient paints among other things.

PieDataset dataset = ...
JFreeChart chart = ChartFactory.createPieChart("My Chart", dataset, false, true, false);

// all possible colors for each piece of the pie
Color[] colors = new Color[] { new Color(232, 124, 35),
        new Color(51, 109, 178), new Color(182, 52, 49),
        new Color(103, 131, 45), new Color(108, 77, 146),
        new Color(46, 154, 183), new Color(151, 64, 64) };

PiePlot plot = (PiePlot) chart.getPlot();
// set each sections inside paint
int i = 0;
for (Object key : dataset.getKeys()) {
    plot.setSectionPaint((Comparable) key, colors[i % colors.length]);
    i++;
}
ug_
  • 11,267
  • 2
  • 35
  • 52
  • Sorry. But I had mentioned before that I do not know the number of sections. I guess I should've mentioned that I do not know the names of the sections as well. With your answer - the data.getKeys() would not return anything relevant. – chrisrhyno2003 Jun 27 '15 at 00:41