JavaFX provides an impressive chart API that allow to draw a wide range of charts. Unfortunately the only scale that is available for XY charts is a linear implementation. Since the javadoc of the API is sometimes a bit rough it took me some times to get figure out how to get a logarithmic scale. After a discussion on mix.oracle.com it turned out that there where to approaches:
the first one is to transform your data with the logarithmic function before injecting it into the chart and to adjust the formatting of the labels to “simulate” a logarithmic scale. Since I don’t really like the idea of manipulating the data to get the expected representation I prefer the second approach:
the second one is to provide your own implementation of a logarithmic Axis. Let’s see how to do this:
Extend the ValueAxis class. There are two methods to implement:
will do the mapping between a data value and its visual position. For a log axis, the implementation will look like this:
protected abstractupdateTickMarks() : Void will define which tick marks should be displayed. The javadoc does not say much about this function. It looks like the main idea is to update the tickMarks sequence of TickMark. The fields of TickMark are weirdly flagged as public-read package, so in oder to instantiate TickMark for our implementation we first need to define a class extending TickMark, let’s say CustomTickMark, and to put it in the package javafx.scene.chart.part in order to be able to set the required fields. After that you just need to update the sequence of tick marks with the marks you want to see on your chart, which can look like this:
Well, you’re now ready to use this LogAxis with your chart. The following example demonstrate the use of this LogAxis as x-scale of a chart.