Dominik Obermaier Dominik Obermaier - 11 months ago 75
Java Question

Nice Label Algorithm for Charts with minimum ticks

I need to calculate the Ticklabels and the Tickrange for charts manually.

I know the "standard" algorithm for nice ticks (see and I also know this Java implementation.

The problem is, that with this algorithm, the ticks are "too smart". That means, The algorithm decides how much ticks should be displayed. My requirement is, that there are always 5 Ticks, but these should of course be "pretty". The naive approach would be to get the maximum value, divide with 5 and multiply with the ticknumber. The values here are - of course - not optimal and the ticks are pretty ugly.

Does anyone know a solution for the problem or have a hint for a formal algorithm description?


You should be able to use the Java implementation with minor corrections.

Change maxticks to 5.

Change the calculate mehod to this:

private void calculate() {
        this.range = niceNum(maxPoint - minPoint, false);
        this.tickSpacing = niceNum(range / (maxTicks - 1), true);
        this.niceMin =
            Math.floor(minPoint / tickSpacing) * tickSpacing;
        this.niceMax = this.niceMin + tickSpacing * (maxticks - 1); // Always display maxticks

Disclaimer: Note that I haven't tested this, so you may have to tweak it to make it look good. My suggested solution adds extra space at the top of the chart to always make room for 5 ticks. This may look ugly in some cases.