Saturday, August 25, 2012

Java XChart Library Now Supports Error Bars

XChart provides a super light-weight and dependency-free charting API for Java. It is open source, hosted on Github, and is licensed with an Apache 2.0 license. I created it over a year ago because I was looking for and couldn't find an easy-to-use plotting library for Java that was similar to the MATLAB's charting tool. I tried JFreeChart of course, but I found that the learning curve was very steep. Like MATLAB's charting functions, I just wanted to simply pass my data to an API, and after a few lines of code, have a plot.

I just recently added support in XChart for making plots with error bars, which is what this post is about. The following demo, shows how to add error bars to an XChart chart. BTW, if you have any feature requests for XChart, please feel free to open a new issue on Github here. For more XChart exmaples go here.

XChart - Open Source Charting API

To use XChart, you first need to get the XChart jar, which is available here. If you use Maven, just add the following to your dependencies in pom.xml:

The XChart artifacts are currently hosted on the Xeiam Nexus repository here:

Error Bars Example Code

package com.xeiam.xchart.example;

import java.util.ArrayList;
import java.util.Collection;

import com.xeiam.xchart.Chart;
import com.xeiam.xchart.series.Series;
import com.xeiam.xchart.series.SeriesColor;
import com.xeiam.xchart.series.SeriesLineStyle;
import com.xeiam.xchart.series.SeriesMarker;
import com.xeiam.xchart.swing.SwingWrapper;

 * Create a Chart with error bars
 * @author timmolter
public class Example8 {

  public static void main(String[] args) {

    // generates data
    int size = 10;
    Collection xData1 = new ArrayList();
    Collection yData1 = new ArrayList();
    Collection errorBars = new ArrayList();
    for (int i = 0; i <= size; i++) {
      yData1.add(10 * Math.exp(-i));
      errorBars.add(Math.random() + .3);

    // Create Chart
    Chart chart = new Chart(600, 400);

    // Customize Chart

    // Series 1
    Series series1 = chart.addSeries("10^(-x)", xData1, yData1, errorBars);

    new SwingWrapper(chart).displayChart();


Resulting Plot

Piece of Cake!!! See also: Java Web Apps - Integrating Charts into a Servlet

No comments: