如何更改JFreeChart的饼图颜色?

时间:2012-10-22 10:21:18

标签: jfreechart

如何自定义JFreeChart图形的颜色。 让我们看看我的java代码:

private StreamedContent chartImage ;

public void init(){
    JFreeChart jfreechart = ChartFactory.createPieChart("title", createDataset(), true, true, false);
    File chartFile = new File("dynamichart");
    ChartUtilities.saveChartAsPNG(chartFile, jfreechart, 375, 300);
    chartImage = new DefaultStreamedContent(new FileInputStream( chartFile), "image/png");
}

public PieDataset createDataset() {
    DefaultPieDataset dataset = new DefaultPieDataset();
          dataset.setValue("J-2", 10);
          dataset.setValue("J-1", 15);
          dataset.setValue("J", 50);
          dataset.setValue("J+1", 20);
          dataset.setValue("J+2", 15);
    return dataset;
}

html页面:

<p:graphicImage id="MyImage" value="#{beanCreateImage.chartImage}" />

3 个答案:

答案 0 :(得分:10)

您可以像这样更改单件的颜色:

JFreeChart chart = ChartFactory.createPieChart("title", createDataset(), true, true, false);
PiePlot plot = (PiePlot) chart.getPlot();
plot.setSectionPaint("J+1", Color.black);
plot.setSectionPaint("J-1", new Color(120, 0, 120));
// or do this, if you are using an older version of JFreeChart:
//plot.setSectionPaint(1, Color.black);
//plot.setSectionPaint(3, new Color(120, 0, 120));

因此,使用您的代码,所有馅饼都会自动着色,在我的代码更改后,J-1J+1会有固定的颜色,其余的会自动着色。

Comparison

答案 1 :(得分:8)

要设置图表的颜色,您可以实现DrawingSupplier界面,在这种情况下,我使用了DefaultDrawingSupplier

public class ChartDrawingSupplier extends DefaultDrawingSupplier  {

    public Paint[] paintSequence;
    public int paintIndex;
    public int fillPaintIndex;

    {
        paintSequence =  new Paint[] {
                new Color(227, 26, 28),
                new Color(000,102, 204),
                new Color(102,051,153),
                new Color(102,51,0),
                new Color(156,136,48),
                new Color(153,204,102),
                new Color(153,51,51),
                new Color(102,51,0),
                new Color(204,153,51),
                new Color(0,51,0),
        };
    }

    @Override
    public Paint getNextPaint() {
        Paint result
        = paintSequence[paintIndex % paintSequence.length];
        paintIndex++;
        return result;
    }


    @Override
    public Paint getNextFillPaint() {
        Paint result
        = paintSequence[fillPaintIndex % paintSequence.length];
        fillPaintIndex++;
        return result;
    }   
}

然后在`init()'方法

中包含此代码
JFreeChart jfreechart = ChartFactory.createPieChart("title", createDataset(), true, true, false);
Plot plot = jfreechart.getPlot();
plot.setDrawingSupplier(new ChartDrawingSupplier());
...

答案 2 :(得分:1)

您可以在从数据集中获取数据时根据标签自定义颜色:

// Add custom colors
        PiePlot plot = (PiePlot) chart.getPlot();

        for (int i = 0; i < dataset.getItemCount(); i++) {
            if(dataset.getKey(i).equals("J+1")){ 
                plot.setSectionPaint(i, Color.black);
            }
        }

您也可以使用switch-case语句或您喜欢的语句。