This example shows how an X/Y chart with two curves can be created using the JFreeChart? package. It is both saved to a file and displayed in a window. The part that's commented out creates a bar chart instead.
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.DefaultXYDataset;
import org.jfree.data.category.DefaultCategoryDataset;
public class XYChartExample extends JFrame {
public static final int NUM_VALUES = 60;
public static void main (String[] args) throws IOException {
double[][] sineValues = new double[2][NUM_VALUES];
double[][] cosineValues = new double[2][NUM_VALUES];
for (int i=0; i<NUM_VALUES; i++) {
sineValues[0][i] = i / 10.0;
cosineValues[0][i] = i / 10.0;
}
for (int i=0; i<NUM_VALUES; i++) {
sineValues[1][i] = Math.sin(sineValues[0][i]);
cosineValues[1][i] = Math.cos(cosineValues[0][i]);
}
DefaultXYDataset dataset = new DefaultXYDataset();
dataset.addSeries("Sine", sineValues);
dataset.addSeries("Cosine", cosineValues);
JFreeChart chart = ChartFactory.createXYLineChart(
"Sine / Cosine Curves",
"X",
"Y",
dataset,
PlotOrientation.VERTICAL,
true,
false,
false
);
File imageFile = new File("sine-cosine.png");
ChartUtilities.saveChartAsPNG(imageFile, chart, 500, 300);
JFrame frame = new XYChartExample();
frame.getContentPane().add(new ChartPanel(chart));
frame.setSize(700, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
OtherOpenSourceProjectsFaq CategoryCodeSamples CodeBarn
|