How to plot line graph using JFreeChart with two arrays: one for x coordinates and the other for y coordinates. I have two functions which gives me two arrays. I want to plot line graph with that arrays is there any possible way that I can do this.
XYSeries series = new XYSeries(" ");
for(int i=((fIndex-1)*2);i<=((tIndex*2)-1);i+=2)
{
series.add(xTValue[i],yTValue[i]);
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series);
return dataset;
Can I do this as above code.
You can use
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series = new DefaultXYSeries();
series.addSeries(" ", new double[][]{xTValue,yTValue});
dataset.addSeries(series);
JFreeChart chart = ChartFactory.createXYLineChart("My chart title",
"my x-axis label", "my y-axis label", dataset);
Alternatively, if you dont specifically need an XYLineChart
, then you can do this by subclassing FastScatterPlot
(I know you want a line plot, but this is an easy way in - you override the render()
method to draw lines!), with something like the following:
public class LinePlot extends FastScatterPlot {
private float[] x, y;
public LinePlot(float[] x, float[] y){
super();
this.x=x;
this.y=y;
}
@Override
public void render(final Graphics2D g2, final Rectangle2D dataArea,
final PlotRenderingInfo info, final CrosshairState crosshairState) {
// Get the axes
ValueAxis xAxis = getDomainAxis();
ValueAxis yAxis = getRangeAxis();
// Move to the first datapoint
Path2D line = new Path2D.Double();
line.moveTo(xAxis.valueToJava2D(x[0], dataArea, RectangleEdge.BOTTOM),
yAxis.valueToJava2D(y[0], dataArea, RectangleEdge.LEFT));
for (int i = 1; i<x.length; i++){
//Draw line to next datapoint
line.lineTo(aAxis.valueToJava2D(x[i], dataArea, RectangleEdge.BOTTOM),
yAxis.valueToJava2D(y[i], dataArea, RectangleEdge.LEFT));
}
g2.draw(line);
}
}
This is a fairly bare-bones implementation - for example no checks that x and y have same number of points, and no addition of colour etc (e.g. g2.setPaint(myPaintColour)
or line type (e.g. g2.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 10.0f, new float[] { 7, 3, 1, 3 }, 0.0f))
would give alternating -•-•
-type lines)