更改图表底部的系列颜色指示器

时间:2013-12-25 12:28:52

标签: java charts jfreechart

我使用jfreechart绘制一些图表,我希望图表栏可以自定义颜色,所以我按照thisthis链接中提到的教程和示例代码进行操作。

条形颜色的问题已经解决,但现在我无法更改图表底部的系列颜色指示器,如下图所示。 enter image description here

有人可以指导我如何根据酒吧改变颜色吗?

修改

class CustomRenderer extends BarRenderer
{
public Paint[] colors;

public CustomRenderer()
{
    this.colors = new Paint[] { Color.green, Color.red };
    /*
     * { 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 ((column % 2 == 0) ? colors[0] : colors[1]);
}
}
//Code for creating the chart in main() method
DefaultCategoryDataset objDataset = new DefaultCategoryDataset();
    objDataset.setValue(10, "POS", "one");
    objDataset.setValue(11, "NEG", "two");
    objDataset.setValue(8, "POS", "three");
    objDataset.setValue(12, "NEG", "four");


    final JFreeChart objChart = ChartFactory.createBarChart(
            "Top Ten Features", // Chart title
            "Features", // Domain axis label
            "POS and NEG value", // Range axis label
            objDataset, // Chart Data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend?
            true, // include tooltips?
            false // include URLs?
            );


    final CategoryPlot categoryPlot = objChart.getCategoryPlot();
    CategoryItemRenderer renderere = new CustomRenderer();
    categoryPlot.setRenderer(renderere);
    final BarRenderer br = (BarRenderer) categoryPlot.getRenderer();
    br.setItemMargin(-1);

    final ChartFrame frame = new ChartFrame("Demo", objChart);
    frame.pack();
    frame.setVisible(true);

1 个答案:

答案 0 :(得分:3)

您的自定义BarRenderer会覆盖getItemPaint(),但原始getLegendItem()会保持不变。这两种方法需要保持一致。您可以覆盖lookupSeriesPaint(),或者更一般地,提供备用DrawingSupplier,如引用文章here所示。