Search code examples
javajfreechart

Multiple axes on the same data


I'm trying to have two axes on the same data.

The data is a couple of DefaultTableXYDatasets. The plot is a XYPlot, and I have two XYLineAndShapeRenderers and one StackedXYAreaRenderer2.

All data is in meters for the y-values, and I want to have one axis displaying it in meters and one axis displaying it in feet. Now this feels like a common thing to do, but I can't decide on the most obvious way to do it. One way that works would be to duplicate the data and have the y-values in feet, then add another NumberAxis and be done with it.

But I thought it would be wiser to subclass NumberAxis, or inject some functionality into NumberAxis to scale the values. Or should I go with the first approach?

What do you think?


Solution

  • Eventually i settled on this solution, it might not be the most elegant but it worked. I have a second axis feetAxis, and added a AxisChangeListener on the first axis called meterAxis. When the meterAxis changes set the range on feetAxis.

    I used SwingUtilities.invokeLater, otherwise the range would be incorrect when zooming out of the chart, then the feetAxis would only go from 0 to 1. Didn't check why though.

    feetAxis = new NumberAxis("Height [ft]");
    metersAxis = new NumberAxis("Height [m]");
    pathPlot.setRangeAxis(0, metersAxis);
    pathPlot.setRangeAxis(1, feetAxis);
    
    metersAxis.addChangeListener(new AxisChangeListener() {
    
       @Override
       public void axisChanged(AxisChangeEvent event) {
    
           SwingUtilities.invokeLater(new Runnable() {
    
               @Override
               public void run() {
                   feetAxis.setRange(metersAxis.getLowerBound() * MetersToFeet, metersAxis.getUpperBound() * MetersToFeet);
                    }
               });
           }
       });