Jfreechart: Is it possible to change the bar color?

不羁的心 提交于 2019-12-04 02:20:20

The magic is the getItemPaint(int,int) method of the BarRenderer class.

An example is at http://javabeanz.wordpress.com/2007/07/04/creating-barcharts-with-custom-colours-using-jfreechart/

What you're trying to do would be something like:

class CustomRenderer extends BarRenderer
{

   public CustomRenderer()
   {
   }

   public Paint getItemPaint(final int row, final int column)
   {
      // returns color depending on y coordinate.
      return (row > 200) ? Color.blue : Color.yellow ;
   }
}

And then after your call to ChartFactory.createBarChart, you do

final CategoryPlot plot = chart.getCategoryPlot();
CategoryItemRenderer renderer = new CustomRenderer();
plot.setRenderer(renderer);
Plot plot = bar.getPlot();
BarRenderer barRenderer = (BarRenderer)plot.getRenderer();
barRenderer.setSeriesPaint(0, Color.gray);

Get a handle to the BarRenderer and call setSeriesPaint(int series, java.awt.Paint paint) on it.

Take a look at this link

JFreeChart: Bar Chart Demo 3: different colors within a series

 /**
 * A custom renderer that returns a different color for each item in a single series.
 */
class CustomRenderer extends BarRenderer {

    /** The colors. */
    private Paint[] colors;

    /**
     * Creates a new renderer.
     *
     * @param colors  the colors.
     */
    public CustomRenderer(final Paint[] colors) {
        this.colors = colors;
    }

    /**
     * Returns the paint for an item.  Overrides the default behaviour inherited from
     * AbstractSeriesRenderer.
     *
     * @param row  the series.
     * @param column  the category.
     *
     * @return The item color.
     */
    public Paint getItemPaint(final int row, final int column) {
        return this.colors[column % this.colors.length];
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!