【问题标题】:Customize bar colors in XYJfree chart自定义 XYJfree 图表中的条形颜色
【发布时间】:2011-11-17 04:22:15
【问题描述】:

如何用不同的颜色绘制不同的条,我尝试使用渲染器,这是我的示例代码:

    public IntervalXYDataset createDataset() throws InterruptedException {
    parseFile();
    final XYSeries series = new XYSeries("Analysis");

    int i=0;
    while(parsedArray[i]!=0)
        {

        series.add(xaxisArray[i], yaxisArray[i]);

        i++;
    }

    final XYSeriesCollection dataset = new XYSeriesCollection(series);

     dataset.setIntervalWidth(0.15);//set width here

    return dataset;
}

这就是我绘制图表的方式:

public className (final String title) throws InterruptedException {
    super(title);
    IntervalXYDataset dataset = createDataset();
    JFreeChart chart = createChart(dataset);
    final ChartPanel chartPanel = new ChartPanel(chart);
     XYPlot plot = (XYPlot) chart.getPlot();
    plot.getRenderer().setSeriesPaint( 0, Color.black);//0 works and paints all 40 bars in black, 1 and above fails. 
             // plot.getRenderer().setSeriesPaint( 1, Color.green);// this fails
    chartPanel.setPreferredSize(new java.awt.Dimension(2000,1000));//(width,height) of display
    setContentPane(chartPanel);

}

我可以设置我在程序中评论的宽度,但是我现在想为不同的条设置颜色,例如我想在图表中获取条并为数组 [0] 绘制红色和[3] 为蓝色,单元格 [17] 为橙色,请您指导我。非常感谢。


【问题讨论】:

    标签: java charts jfreechart bar-chart


    【解决方案1】:

    你想要做的是:

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.getRenderer().setSeriesPaint(1, Color.yellow);
    

    将 1 替换为您要更改其颜色的条的(从零开始的)索引。

    编辑以回复评论:

    List<Color> myBarColors = .....
    
    XYPlot plot = (XYPlot) chart.getPlot();
    XYItemRenderer renderer = plot.getRenderer();
    
    for (int i = 0; i < 40; i++) {
        renderer.setSeriesPaint(i, myBarColors.get(i));
    }
    

    编辑 2:被误解的 OPs 问题,cmets 中的新解决方案。

    【讨论】:

    • 这是一种直截了当的方法;但是Color.yellow 是第四个默认颜色,所以超过三个系列都失败了。
    • 您好,我试过这样做,它适用于值 '0',如 setSeriesPaint(0, Color.yellow);但我有大约 40 条 - 这个循环 40 次:-(series.add(xaxisArray[i], yaxisArray[i]);) 你能帮我解决这个错误吗?我想为每个条设置颜色。非常感谢。
    • @helloMaga 我不知道究竟你想做什么,但我更新了我的答案以显示循环设置颜色。
    • 你好乔丹,请看我上面的问题,我已经声明了我的问题。
    • @helloMaga 好的,我又看了一下原帖。我认为您为数据集使用了错误的类。我面前没有任何东西可以对此进行测试,但请尝试使用 CatagoricalDataset 或 XYBarDataset。如果您使用这些 setSeriesPaint() 方法应该适用于您正在尝试做的事情。
    【解决方案2】:

    我找到了答案 创建两个系列,然后添加所需的条数并为每个系列设置颜色。使用 setSeriesPaint

    【讨论】:

      【解决方案3】:

      最灵活的方法是在自定义XYBarRenderer 中覆盖AbstractRenderergetItemPaint() 方法,如hereXYLineAndShapeRenderer 所示。

      【讨论】:

        猜你喜欢
        • 2014-08-24
        • 2015-05-14
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多