2011-09-14 17 views
3

如何画不同颜色不同的酒吧,我试图用渲染器,这里是我的示例代码:在XYJfree图表自定义栏的颜色

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); 

} 

我可以设置宽度,因为我在我的程序有评论,但是我现在要为不同的酒吧的颜色,例如我想吧握在图表,绘制红色阵列[3]为蓝色,c为橙色埃尔[17],请你指导我这个。非常感谢你。


回答

2

我找到了答案 创建两个系列,然后添加您想要的有多少条,并为每个系列设置颜色。使用setSeriesPaint

3

你想要做的是以下几点:

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:被误读的有机磷农药的问题,在评论新的解决方案。

+0

这是一个直截了当的方法;但是'Color.yellow'是第四种默认颜色,所以它会失败超过三个系列。 – trashgod

+0

你好,我试过这样做,它的值为'0',如setSeriesPaint(0,Color.yellow);但我有大约40个酒吧 - 这个循环40次:-(series.add(xaxisArray [i],yaxisArray [i]);)你能帮我解决这个错误。我想为每个栏设置颜色。非常感谢。 –

+1

@helloMaga我完全不知道*你正在尝试做什么,但我更新了我的答案,以便在循环中显示设置颜色。 –