Different color for different series in XYline chart JFreeChart

Rohit Elayathu picture Rohit Elayathu · Apr 12, 2012 · Viewed 22.8k times · Source

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

Answer

Rohit Elayathu picture Rohit Elayathu · Apr 13, 2012

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);