简体   繁体   English

JFreeChart:如何在同一图表上绘制折线图和散点图

[英]JFreeChart: How to plot a line graph and a scatter on same chart

i have two sets of data 我有两组数据

int[] x1 = {1,2,3,4,5,6,7,8,9,10};
int[] y1 = {1,2,3,5,6,8,9,10,14,11};

int[] x2 = {1,2,3,4,5,6,7,8,9,10};
int[] y2 = {0,2,3,5,0,8,9,8,14,11};

int[] z2 = {1,2,3,1,2,3,1,2,3,1};

I want to plot the x1,y1 as an XYLineChart and then plot x2,y2 as a scatter on the same plot without a line. 我想将x1,y1绘制为XYLineChart ,然后将x2,y2绘制为不带线的相同绘图上的散点图。

I also need each scatter point of xy,y2 to be a different color depending on the value of z2 (1=Color.red, 2=Color.green, 3=Color.blue) 我还需要xy,y2每个散点都是不同的颜色,具体取决于z2的值(1=Color.red, 2=Color.green, 3=Color.blue)

How can i do this? 我怎样才能做到这一点?

So far i have: 到目前为止,我有:

JPanel panel_1 = new JPanel();
panel_1.setLayout(new BorderLayout(0, 0));
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series1 = new XYSeries("series1");
for(int i=0; i<x1.length; i++){
    series1.add(x1[i],y1[i]);
}
dataset.add(series1);
JFreeChart chart = ChartFactory.createXYLineChart("Title", "x", "y", dataset, PlotOrientation.VERTICAL, false, false, false);
ChartPanel cp = new ChartPanel(chart);
panel_1.add(cp, BorderLayout.CENTER);

This gets the line graph sorted. 这会将线图排序。 I now need to code the scatter plot for x2,y2 (with colors described above) which is where im stuck. 我现在需要编码x2,y2 (上面描述的颜色)的散点图x2,y2这是我卡住的地方。

The createXYLineChart() method will create a chart that uses an XYLineAndShapeRenderer . createXYLineChart()方法将创建一个使用XYLineAndShapeRenderer的图表。 So fetch the renderer from the plot and cast it to XYLineAndShapeRenderer. 因此,从绘图中获取渲染器并将其转换为XYLineAndShapeRenderer。 Then you can call the methods setSeriesLinesVisible() and setSeriesShapesVisible() to control, for each series, whether shapes and/or lines are drawn for the data items. 然后,您可以调用方法setSeriesLinesVisible()setSeriesShapesVisible()来控制每个系列是否为数据项绘制形状和/或线。 That way you can use a single renderer and dataset, which makes things simpler. 这样,您可以使用单个渲染器和数据集,这使事情变得更简单。

Your requirement to change the colors depending on another data value requires a little more work. 您需要根据其他数据值更改颜色需要更多工作。 You should subclass the XYLineAndShapeRenderer class and override the getItemPaint(int, int) method. 您应该继承XYLineAndShapeRenderer类并重写getItemPaint(int,int)方法。 Here you can return any color you want for a data item. 在这里,您可以返回数据项所需的任何颜色。 The default implementation looks at the series index and returns the color for the series. 默认实现查看系列索引并返回系列的颜色。 You need to look at the item index as well, then do a lookup in your table of z-values and decide what color to return. 您还需要查看项目索引,然后在z值表中查找并确定要返回的颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM