7

如何自定义 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}" />
4

3 回答 3

13

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

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-1并且J+1具有固定颜色,其余部分会自动着色。

比较

于 2012-10-22T10:50:33.667 回答
10

要为图表设置颜色,您可以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());
...
于 2012-10-22T11:22:16.337 回答
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 语句或您喜欢的语句。

于 2016-07-22T15:20:17.187 回答