如何动态设置堆积条形图系列颜色?

How to set stacked bar chart series color dynamically?

我在 eclipse 的 JasperSoft 6.3.1 中有一个堆叠条形图,我正在尝试根据系列显示颜色。该图表显示随机颜色,而不是为特定系列分配单一颜色。

jrxml

<categorySeries>
    <seriesExpression><![CDATA[$F{name}]]></seriesExpression>
    <categoryExpression><![CDATA[$F{time}]]></categoryExpression>
    <valueExpression><![CDATA[$F{value}]]></valueExpression>
</categorySeries>
</categoryDataset>
    <barPlot>
        <plot>
            <seriesColor $F{name}.equals("JANUARY")?color="#756D72":color="" seriesOrder="0" />
            <seriesColor $F{name}.equals("MARCH")?color="#4B5154":color="" seriesOrder="1" />
            <seriesColor $F{name}.equals("JUNE")?color="#090A09":color="" seriesOrder="2"/>
        </plot>
    <itemLabel/>
    <categoryAxisFormat>
    ....

我正在尝试使用 if 语句将图表系列颜色分配给特定系列名称。我如何在碧玉报告中实现这一目标?

If the series name is JANUARY the color should be black, and if there is no data for JANUARY the black color should not be used.

我猜你已经注意到了,你可以 not 在 xml 标签中做 if 语句,jrxml 将不会编译,因为它不再有效 xml。

解决方案是实现您自己的 JRChartCustomizer

例子

java

找到不同的系列名称并根据名称Paint设置渲染器

public class BarColorCustomizer implements JRChartCustomizer {

    @Override
    public void customize(JFreeChart jfchart, JRChart jrchart) {
        //Get the plot
        CategoryPlot  plot = jfchart.getCategoryPlot();
        //Get the dataset
        CategoryDataset dataSet = plot.getDataset();
        //Loop the row count (our series)
        int rowCount = dataSet.getRowCount();
        for (int i = 0; i < rowCount; i++) {
            Comparable<?> rowKey = dataSet.getRowKey(i);
            //Get a custom paint for our series key
            Paint p = getCustomPaint(rowKey);
            if (p!=null){
                //set the new paint to the renderer
                plot.getRenderer().setSeriesPaint(i, p);
            }
        }

    }

    //Example of simple implementation returning Color on basis of value
    private Paint getCustomPaint(Comparable<?> rowKey) {
        if ("JANUARY".equals(rowKey)){
            return Color.BLACK;
        }
        return null;
    }
}

jrxml

在图表标签上设置 customizerClass 具有完整包名称的属性

<barChart>
    <chart evaluationTime="Report" customizerClass="my.custom.BarColorCustomizer">
    ....
</barChart>