Creating BarCharts with custom colours using JFreeChart

This can be achieved by extending the BarRenderer. BarRenderer is responsible for all kind of UI related things like setting the font, setting the colors, setting the alignment etc etc. Rather we can say everything. The same can be achieved by extending corresponding renderer.

Here the getItemPaint(row, col) has been overridden to achieve the custom colors.

CustomRenderer:

import org.jfree.chart.renderer.category.BarRenderer; 
import java.awt.Color; 
import java.awt.Paint;
class CustomRenderer extends BarRenderer 
{ 
 private Paint[] colors;
 public CustomRenderer() 
 { 
    this.colors = new Paint[] {Color.red, Color.blue, Color.green, 
      Color.yellow, Color.orange, Color.cyan, 
      Color.magenta, Color.blue}; 
 }
 public Paint getItemPaint(final int row, final int column) 
 { 
    // returns color for each column 
    return (this.colors[column % this.colors.length]); 
 } 
}
 

Using custom renderer with the CategoryPlot:

final JFreeChart chart = ChartFactory.createBarChart( 
   "chart title", 
   "x axis label", 
   "y axis label ", 
   dataset, 
   PlotOrientation.VERTICAL, 
   false,                 
   true, 
   false 
);
chart.setBackgroundPaint(Color.lightGray);
// get a reference to the plot for further customisation... 
final CategoryPlot plot = chart.getCategoryPlot(); 
CategoryItemRenderer renderer = new CustomRenderer(); 
plot.setRenderer(renderer);
 

Other useful links:
Creating a 3D BarChart using JFreeChart
Creating Time Series charts using JFreeChart
Creating Pie Chart using JFreeChart (Using plot)
Creating Pie Chart using JFreeChart

Advertisements