简体   繁体   中英

Dynamic Pie chart in Jfreechart - how to set colours

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 ?

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++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM