JFreeChart: How to plot a line graph and a scatter on same chart
Asked Answered
I

1

3

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.

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)

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.

Ironlike answered 21/10, 2013 at 18:54 Comment(1)
Take a look here: #6076633 not exactly the same but related. Have you tried adding a second renderer? See code.google.com/p/swing-ui-hxzon/source/browse/trunk/jfreechart/… for a copy of the sample code.Copycat
C
8

The createXYLineChart() method will create a chart that uses an XYLineAndShapeRenderer. So fetch the renderer from the plot and cast it to 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. 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. 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.

Chavers answered 22/10, 2013 at 6:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.