Tomáš Zato
Tomáš Zato

Reputation: 53149

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());
}

Upvotes: 0

Views: 1066

Answers (2)

copeg
copeg

Reputation: 8348

If your data does not require the use of Categories, you can use an XYDataset, and create an XY plot eg using ChartFactory.createXYLineChart.

DefaultXYDataset ds = new DefaultXYDataset();
//generate random data as an example
double[][] data = new double[2][1000];
for ( int i = 0; i < 1000; i++ ){
    data[0][i] = i;
    data[1][i] = (Math.random() * 100);
}
ds.addSeries("Time", data);
JFreeChart chart = ChartFactory.createXYLineChart("Test", "Time", "Y-Axis", ds, PlotOrientation.VERTICAL, false,false,false); 

In this manner, problem (2) should take care of itself (and you could make use of the DateAxis class for rendering the time). For problem (1), using this type of axis you can just invert it:

myChart.getXYPlot().getRangeAxis().setInverted(true);

Upvotes: 2

Eric Leibenguth
Eric Leibenguth

Reputation: 4277

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

Upvotes: 2

Related Questions