Search code examples
javajfreechart

Create JFreeChart with both axes keyed numerically


I am making a chart that displays network latency and connection failure rate on graph. I am using DefaultCategoryDataset to store the data, but the problem is, that this dataset uses String for the X axis values:

  DefaultCategoryDataset dataset = new DefaultCategoryDataset( );
  dataset.addValue( 15 , "Line name" , "X value" );

Since I render packets based on Unix time in miliseconds, it ends up looking like this:

image description

I'd like to fix it so that:

  1. New values (larger timestamp) appear to the right, not left
  2. X labels too close to each other are inteligently merged, as on this image: image description

To generate the dataset, I run over array of samples and end up with two HashMap<String, Double> representing average latency and failure rate. These are then assigned as follows:

//Latency line
for (Map.Entry<String, Double> entry : time.entrySet())
{
  dataset.addValue(entry.getValue(), "Average ping [ms]", entry.getKey());
}
//Fail rate line
for (Map.Entry<String, Double> entry : fail_rate.entrySet())
{
  dataset.addValue(entry.getValue()*100, "Fail rate [%]", entry.getKey());
}

Solution

  • For this type of graph I think you should use a XYDataset with TimeSeriesand DateAxis. There is one example demonstrated here: http://www.jfree.org/jfreechart/api/javadoc/src-html/org/jfree/chart/demo/TimeSeriesChartDemo1.html

    You can also use a custom Timeline implementation for your DateAxis, in particular to control the orientation of the dates (more recent to the right). More information here: http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/axis/Timeline.html