Rohit Elayathu
Rohit Elayathu

Reputation: 639

Different color for different series in XYline chart JFreeChart

I have created XY line chart using JFreeChart, having two datasets, I want both the lines to be in different colors. I tried using following code-

  XYPlot plot = chart.getXYPlot();
  XYItemRenderer xyir = plot.getRenderer();
  xyir.setSeriesPaint(0, Color.GREEN);
  plot.setDataset(0, xyDataset1);

  xyir.setSeriesPaint(1, Color.blue);
  plot.setDataset(1, xyDataset2);

Also I have tried using following code, where I am using different renderer (don't know whether this is correct way to do it)-

  XYPlot plot1 = chart.getXYPlot();
  XYPlot plot2 = chart.getXYPlot();

  XYItemRenderer xyir1 = plot1.getRenderer();
  xyir1.setSeriesPaint(0, Color.GREEN);
  plot1.setDataset(0, xyDataset1);

  XYItemRenderer xyir2 = plot2.getRenderer();
  xyir2.setSeriesPaint(1, Color.blue);
  plot2.setDataset(1, xyDataset2);

In both the cases its printing both the lines in blue color. What's wrong?? Any suggestions??

Upvotes: 9

Views: 25603

Answers (3)

Impe
Impe

Reputation: 1

Try to set the Series paint to null in the renderer setSeriesPaint(null);

If you take a look at the source it first checks to see if the paint is !null, then uses the base color.

If null it uses the colors associated with the time serie from a lookup table.

Upvotes: -1

Rohit Elayathu
Rohit Elayathu

Reputation: 639

Found the solution, it works for me, using two different Renderer, earlier i was not doing it properly--

 XYPlot plot = chart.getXYPlot();
  plot.setDataset(0, xyDataset1);
  plot.setDataset(1, xyDataset2);
  XYLineAndShapeRenderer renderer0 = new XYLineAndShapeRenderer(); 
  XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer(); 
  plot.setRenderer(0, renderer0); 
  plot.setRenderer(1, renderer1); 
  plot.getRendererForDataset(plot.getDataset(0)).setSeriesPaint(0, Color.red); 
  plot.getRendererForDataset(plot.getDataset(1)).setSeriesPaint(0, Color.blue);

Upvotes: 19

trashgod
trashgod

Reputation: 205875

The approach shown works in this example, and a single renderer should be sufficient. An sscce may help isolate the problem.

To control individual items, you can override getItemPaint(), shown here.

Upvotes: 3

Related Questions