Sunday, 16 January 2011

Java: Drawing charts it's easy



Recently I need to draw a chart, and after short search I found great library JFreeChart. It provides drawing and saving charts to the png file.


Here is the code sample:
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
 
public class MyChart {
  public static void main(String[] args) {
    XYSeries series = new XYSeries("cos(a)");
 
    //calculating points
    for(float i = -10; i < 10; i+=0.1){
      series.add(i, Math.cos(i));
    }
 
    XYDataset xyDataset = new XYSeriesCollection(series);

    //creating chart
    JFreeChart chart = ChartFactory
        .createXYLineChart("y = cos(x)", "x", "y",
                           xyDataset, 
                           PlotOrientation.VERTICAL,
                           true, true, true);
    JFrame frame = 
        new JFrame("Chart");

    //adding chart to the frame
    frame.getContentPane()
        .add(new ChartPanel(chart));
    frame.setSize(400,300);
    frame.show();
  }
}
References:
JFreeChart tutorial

No comments:

Post a Comment