node-modulestelegram-botchartjs-2.6.0

How can I fix the issue where the column values on my Chart JS chart are displayed in the wrong place?


I wrote a telegram bot on NodeJS that shows a bar graph of sales on request.

enter image description here

enter image description here

The first graph shows the correct arrangement of column values. The second one is incorrect. The correct graph appears only when the first query is processed, and all repeated queries draw the wrong graph (with incorrect display of column values).

const { ChartJSNodeCanvas } = require('chartjs-node-canvas');
 
    const width = 600; // Chart width
    const height = 400; // Chart height

    const chartCallback = (ChartJS) => {
        ChartJS.defaults.font.size = 14; // Set default font size
    };

    const canvas = new ChartJSNodeCanvas({ width, height, chartCallback });

    const chartData = {
        labels: ['План', 'Факт', 'Прогноз'],
        datasets: [
            {
                label: 'Сумма',
                data: [salesTarget, monthSum, monthForcastSum],
                backgroundColor: 'rgba(54, 162, 235, 0.5)', // Bar background color
                borderColor: 'rgba(54, 162, 235, 1)', // Bar border color
                borderWidth: 1, // Bar border width
            },
        ],
    };

    const chartOptions = {
        responsive: false, // Disable automatic responsiveness
        scales: {
            y: {
                beginAtZero: true, // Start Y axis from zero
                ticks: {
                    callback: (value) => value.toLocaleString('ru-RU'), // Format Y axis values
                },
            },
        },
        plugins: {
            datalabels: {
                anchor: 'end',
                align: 'top',
                font: {
                    size: 20,
                    weight: 'bold',
                },
                formatter: (value) => value.toLocaleString('ru-RU'), // Format value labels
                color: 'rgba(54, 162, 235, 1)', //'black', // Label text color
                textAlign: 'center',
            },
            title: {
                display: true,
                text: `Продажи за ${currentMonth} ${moment().format('YYYY')} (${moment().format('DD.MM - HH:mm')})`,
                color: 'rgba(54, 162, 235, 1)',
                font: {
                    size: 20,
                    weight: 'bold',
                    lineHeight: 1.2,
                },
            }
        },
    };

    const configuration = {
        type: 'bar', // Bar chart type
        data: chartData,
        options: chartOptions,
        plugins: [ChartDataLabels], // Register the plugin
    };

    const image = await canvas.renderToBuffer(configuration);

Tell me how to deal with this problem.


Solution

  • const chartOptions = {
    //...
    plugins: {
        datalabels: {
            anchor: 'start', // Заменить 'end' на 'start'
            //...
        },
        //...
    },
    

    };