Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 828
Rohit Elayathu Avatar asked Apr 12 '12 13:04

Rohit Elayathu


2 Answers

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);
like image 77
Rohit Elayathu Avatar answered Oct 30 '22 20:10

Rohit Elayathu


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.

like image 3
trashgod Avatar answered Oct 30 '22 21:10

trashgod