javascriptjquerychart.jschartjs-plugin-annotation

annotation library for chartjs


annotation library for chartjs, i have chart with labels 0, 1, 4, 8, 12, 15, 20, 24, 25, 28, 32, and i have label 7.5 for adding vertical line to that label but this library adding it between 24 and 25

my code:

for (const valueObj of valueList) {
    const {value, annotationId, color} = valueObj;
    const floatVal = parseFloat(value);

    const annotation = {
        type: 'line',
        mode: 'vertical',
        scaleID: 'x',
        value: floatVal,
        borderColor: color,
        borderWidth: 2,
        label: {
            content: `x = ${value}`,
            enabled: true,
            position: 'top'
        }
    };

    chart.options.plugins.annotation.annotations[annotationId] = annotation;

}

chart.update();

the result of that is :

what can i do, or how can i change this function to working correctly


Solution

  • This is happening because you are setting the labels as an array of numbers and the annotation plugin, when the scale is a category one, use the index of the array when the value is set as number. In fact, 7.5 is the index between values 24 and 25.

    To have the line at value 7.5 you need to set the annotation value to 2.875.

    Why? Because the value 7.5 is between index 2 and 3 and the difference of the values at index 2 (value 4) and 3 (value 8) is 4. Therefore the value is:

    ((7.5 - 4) / 4) + 2 = 2.875
            |    |    |
            |    |    +--> base index 
            |    +--> difference between index 3 and 2
            +--> value at 2