JFreeChart x axis scale

Biscuit128 picture Biscuit128 · Dec 27, 2012 · Viewed 18.8k times · Source

I have a JFree XY Line chart which always starts at x = 0. Then based on user defined settings from a properties file, the application increments based on that number (this represents the time in minutes).

For example, x = 0 to start the user defined setting is 5 so the scale goes 0, 5, 10, 15, 20…, or the user setting is 3 so it goes 0, 3, 6, 9, 12… Pretty simple.

The issue I am having is the way in which the graph starts. If I start at 0, then 0 is in the middle of the graph rather than at the bottom left with -0.0000005, -0.000004, -0.000003… 0.000000 , 0.000001 , 0.000002… 0.000005

How can I just manually add the scale at the bottom, i.e. define it should be increments of 2 and then maintain it?

Answer

obourgain picture obourgain · Jan 4, 2013

You should use NumberAxis, which contains a lot of methods to define the scale of your chart.

Example :

// Create an XY Line chart
XYSeries series = new XYSeries("Random Data");
series.add(1.0, 500.2);
series.add(10.0, 694.1);
XYSeriesCollection data = new XYSeriesCollection(series);
JFreeChart chart = ChartFactory.createXYLineChart("XY Series Demo", "X", "Y", data,
                                                  PlotOrientation.VERTICAL, 
                                                  true, true, false);

// Create an NumberAxis
NumberAxis xAxis = new NumberAxis();
xAxis.setTickUnit(new NumberTickUnit(2));

// Assign it to the chart
XYPlot plot = (XYPlot) chart.getPlot();
plot.setDomainAxis(xAxis);