Customize bar colors in XYJfree chart

2019-02-25 10:26发布

问题:

how to paint different bars in different colors, I tried to use renderer, here is my sample code:

    public IntervalXYDataset createDataset() throws InterruptedException {
    parseFile();
    final XYSeries series = new XYSeries("Analysis");

    int i=0;
    while(parsedArray[i]!=0)
        {

        series.add(xaxisArray[i], yaxisArray[i]);

        i++;
    }

    final XYSeriesCollection dataset = new XYSeriesCollection(series);

     dataset.setIntervalWidth(0.15);//set width here

    return dataset;
}

and this is how I am drawing the graph:

public className (final String title) throws InterruptedException {
    super(title);
    IntervalXYDataset dataset = createDataset();
    JFreeChart chart = createChart(dataset);
    final ChartPanel chartPanel = new ChartPanel(chart);
     XYPlot plot = (XYPlot) chart.getPlot();
    plot.getRenderer().setSeriesPaint( 0, Color.black);//0 works and paints all 40 bars in black, 1 and above fails. 
             // plot.getRenderer().setSeriesPaint( 1, Color.green);// this fails
    chartPanel.setPreferredSize(new java.awt.Dimension(2000,1000));//(width,height) of display
    setContentPane(chartPanel);

}

I am able to set the width as I have commented in my program, however I now want to set the color for different bars, for example I want to get hold of bar in chart and draw red for array[0] and blue for [3] and orange for cell[17], can you please guide me on this. Thank you very much.


回答1:

What you want to do is the following:

XYPlot plot = (XYPlot) chart.getPlot();
plot.getRenderer().setSeriesPaint(1, Color.yellow);

Replace 1 with the (zero-based) index of the bar whose color you would like to change.

Edit to respond to comment:

List<Color> myBarColors = .....

XYPlot plot = (XYPlot) chart.getPlot();
XYItemRenderer renderer = plot.getRenderer();

for (int i = 0; i < 40; i++) {
    renderer.setSeriesPaint(i, myBarColors.get(i));
}

Edit 2: Misunderstood OPs problem, new solution in comments.



回答2:

The most flexible approach is to override the getItemPaint() method of AbstractRenderer in a custom XYBarRenderer, as shown here for XYLineAndShapeRenderer.



回答3:

I found the answer Create two series, and then add how many ever bars you want and set color for each series. using setSeriesPaint