Chartjs-Chart – Y Axis display value and step calculation

0👍

General idea :

- Specify how many ticks you want on your axis ( tick_count )
- Find the range of the data ( max - min )
- tick_increment = range / tick_count, rounded down to integer
- tick_value = min
- LOOP
    tick_value += tick_increment

This seems strightforward. The trick is all the extra code required to handle special cases.

Here is some C++ code that handles some of them

std::vector< double > tickValues(
    double mn, double mx )
{
    std::vector< double > vl;
    double range = mx - mn;
    if( range < minDataRange )
    {
        // plot is single valued
        // display just one tick
        vl.push_back( mn );
        return vl;
    }
    double inc = range / 4;
    double tick;
    if( inc > 1 )
    {
        inc = ( int ) inc;
        tick  = ( int ) mn;
    }
    else
    {
        tick = mn;
    }
    while( true )
    {
        double v = tick;
        if( v > 100)
            v = ((int) v / 100 ) * 100;
        else if( v > 10 )
            v = ((int) v / 10 ) * 10;
        vl.push_back( v );
        tick += inc;
        if( tick >= mx )
            break;
    }
    vl.push_back( mx );
    return vl;
}

Code for complete 2D plotting class https://github.com/JamesBremner/windex/blob/master/include/plot2d.h

Recommendation: A full featured, robust 2D plotter ready to handle arbitrary data sets requires a tremendous amount of code, so rather than spinning up your own, it might be better not to reinvent the wheel and find a suitable library or application.

Leave a comment