如何解决 Chart JS 图表上的列值显示在错误位置的问题?

问题描述 投票:0回答:1

我在 NodeJS 上编写了一个电报机器人,可根据请求显示销售条形图。

第一张图显示了列值的正确排列。第二个是不正确的。仅当处理第一个查询时才会出现正确的图形,所有重复的查询都会绘制错误的图形(列值显示不正确)。

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);

告诉我如何处理这个问题。

node-modules telegram-bot chartjs-2.6.0
1个回答
0
投票
const chartOptions = {
//...
plugins: {
    datalabels: {
        anchor: 'start', // Заменить 'end' на 'start'
        //...
    },
    //...
},

};

© www.soinside.com 2019 - 2024. All rights reserved.