Search code examples
javajfreechart

How to set a margin on a ValueAxis with auto-calculate disabled?


I'm using JFreeChart for displaying charts in PDF with Apache PdfBox.

My problem is this: I have a Scatter Plot Chart (image attached) that has fixed lower and upper bound, so auto-calculate is not an option. The chart displays a blue dot with the result. However, if the value of dot is 0 or 2 (edge values), the dot is cut out, so I need to set up a margin in this case. I tried with xAxis.setUpperMargin, but with no luck.

This is part of the code:

NumberAxis xAxis = (NumberAxis) xyPlot.getDomainAxis();
double tickSize = maxValue > 10 ? 1 : 0.5;
xAxis.setTickUnit(new NumberTickUnit(tickSize));
xAxis.setRange(1, maxValue);

Chart Image


Solution

  • As you have observed, a "margin is added only when the axis range is auto-calculated—if you set the axis range manually, the margin is ignored." Alternatively, you can add a suitable margin when manually setting the range. Starting from this example, the following change to adjustAxis() adds a 10% margin to each end of each axis, producing the result shown.

    axis.setRange(-1.1, 1.1);
    

    scatter plot with margin