JFreeChart axis label in Hours

2019-08-10 02:17发布

问题:

I have data e.g. (1,3600), (2,4400), ... (33,15000) Where in (1,3000) -> 1 is a number -> 3600 is seconds

If put in chart, the axis would show the "second" as number. I have set a code to show axis label in 1 hour interval.

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

// Assign it to the chart
xyPlot.setDomainAxis(xAxis);

So now the axis labels are: 0 ... 3600 ... 7200 ... 10.800 ...

How to make the axis labels show in hours? (0 ... 1 ... 2 ... 3 ...)

回答1:

One approach is to scale your data by 1000 to represent milliseconds from the epoch. Then you can use a SimpleDateFormat with a suitable TimeZone to get the desired effect.

DateAxis axis = new DateAxis("Hour");
SimpleDateFormat format = new SimpleDateFormat("H");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
axis.setDateFormatOverride(format);

The hours are limited to between 0 and 23, any idea how to overcome this?

You can experiment with other formats, e.g. "D:H". Alternatively, scale by 1/3600 to represent hours and use a NumberAxis with integer tick units.

NumberAxis axis = new NumberAxis();
axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());