Chart.js Display Prediction Data

Viewed 14

I'm trying to make a chart to display the revenues of a company, and I would like to display the predictions for this year but with a borderDash segment option. How could I do that? I tried this and I have no clue how to do it.

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

Here's the expected result: Image of the expected result

I hope somebody can help me with that. Thanks in advance.

1 Answers

What about adding an extra dataset for your forecast data. Style this second set with a dashed line? Yes, that results in 2 datasets. One for the data and one for the prediction. Hope that helps.

As example (not tested, just as example):

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:[] });

Related