Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the color of jfreechart piechart

I want to change the color of the "pieces" of pie in my jfreechart PieChart3D, this is the code that renders the piechart:

<% response.setContentType("image/png"); %><%@page import="org.jfree.data.general.*"%><%@page import="org.jfree.chart.*"%><%@page import="org.jfree.chart.plot.*"%><%@page import="java.awt.Color" %><%

        DefaultPieDataset ds = (DefaultPieDataset)session.getAttribute("usagePieOutputDataset");

  JFreeChart chart = ChartFactory.createPieChart3D
  (
   null,  // Title
   ds,  // Dataset
   false,  // Show legend
   false,  // Use tooltips
   false  // Configure chart to generate URLs?
  );

     chart.setBackgroundPaint(Color.WHITE);
     chart.setBorderVisible(false);

  PiePlot3D plot = ( PiePlot3D )chart.getPlot();
  plot.setDepthFactor(0.0);
  plot.setLabelGenerator(null); //null means no labels

  plot.setLabelOutlinePaint(Color.LIGHT_GRAY);
  plot.setLabelFont(new java.awt.Font("Arial",  java.awt.Font.BOLD, 10));


  ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 150, 144);
%>

Any help is highly appreciated.

like image 742
timkl Avatar asked Dec 29 '22 08:12

timkl


2 Answers

The color for each section is normally populated from the plot's DrawingSupplier. You can override the defaults, though, by calling

PiePlot.setSectionPaint(Comparable key, Paint paint);

With, this though, you'll need to set each section manually. If you just want a different set of colors, it looks like you could implement DrawingSupplier.

like image 137
Reverend Gonzo Avatar answered Dec 31 '22 22:12

Reverend Gonzo


You can use

 Color[] colors = {Color.green, Color.red, Color.yellow .. /* size of data set */}; 
 PieRenderer renderer = new PieRenderer(colors); 
 renderer.setColor(plot, ds);

and as an inner class:

static class PieRenderer 
    { 
        private Color[] color; 

        public PieRenderer(Color[] color) 
        { 
            this.color = color; 
        }        

        public void setColor(PiePlot plot, DefaultPieDataset dataset) 
        { 
            List <Comparable> keys = dataset.getKeys(); 
            int aInt; 

            for (int i = 0; i < keys.size(); i++) 
            { 
                aInt = i % this.color.length; 
                plot.setSectionPaint(keys.get(i), this.color[aInt]); 
            } 
        } 
    } 
like image 37
asyard Avatar answered Dec 31 '22 22:12

asyard