Chart.js显示预测数据

xt0899hw  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(210)

我正在制作一个图表来显示某公司的收入,我想显示今年的预测,但要使用borderDash段选项。我该怎么做呢?我试过了,但我不知道该怎么做。

const lineCanvas = document.getElementById("lineCanvas");

const prediction = (ctx, value) => ctx.dataIndex = 4 ? value : undefined;

const lineChart = new Chart(lineCanvas, {
type: "line",
data: {
    labels: ["2019", "2020", "2021", "2022"],
    datasets: [{
        label: "Revenues",
        data: [2195, 2225, 2166, 2250],
        backgroundColor: "orange",
        borderColor: "orange",
        segment: {
            borderDash: ctx => prediction(ctx, [6, 6])
        }
    }]
},
options: {
    scales: {
        y: {
            ticks: {
                font: {
                    size: 18
                },
                stepSize: 10
            },
            title: {
                display: true,
                text: "Total",
                font: {
                    size: 14
                }
            },

        },
        x: {
            ticks: {
                font: {
                    size: 18
                }
            },
            title: {
                display: true,
                text: "Year",
                font: {
                    size: 14
                }
            }
        }
    },
    plugins: {
        title: {
            display: true,
            text: "Company's Revenues",
            font: {
                size: 22
            },
            padding: 0
        },
        subtitle: {
            display: true,
            text: "(in millions of €)",
            font: {
                size: 18
            },
            padding: 0
        }
    }
}
});

以下是预期结果:Image of the expected result
我希望有人能帮我。提前感谢。

bvuwiixz

bvuwiixz1#

为预测数据添加一个额外的数据集如何?使用虚线设置第二个数据集的样式?是的,这样会产生2个数据集。一个用于数据,一个用于预测。希望这对您有所帮助。
作为示例(未测试,仅作为示例):

const lineChart = new Chart(lineCanvas, {
type: "line",
data: {
    labels: ["2019", "2020", "2021", "2022"],
    datasets: [{
        label: "Revenues",
        data: [2195, 2225, 2166, 2250],
        backgroundColor: "orange",
        borderColor: "orange",
    }, {
        label: "Revenues",
        data: [2195, 2225, 2166, 2250, 6000, 9000], /* Add the extra data points */
        borderColor: "red" /* Whatever style you like */
    }]
}, options:[] });

相关问题