Background-color for area below line chart in chartJs?
Asked Answered
I

1

7

I am creating a chart to render some data using chart js.

  const data = {
    labels: ["1 Dec", "8 Dec", "16 Dec", "31 Dec"],
    datasets: [
      {
        label: "Sales Made",
        data: [3, 7, 4, 5],
        borderColor: ["#03A9F5"],
      },
    ],
  };
  const options = {
    tension: 0.4,
    title: {
      display: true,
      text: "linechrt",
    },
    scales: {
      y: [
        {
          display: true,
          stacked: true,
          ticks: {
            beginAtZero: true,
            steps: 10,
            stepValue: 5,
            min: 0,
            max: 100,
          },
        },
      ],
    },
  };

now I've looked at online tutorials and even the documentation but I've not gotten a clear answer on how to paint the area below the line. ChartJs has a lot of versions and previous answers to this question especially here on Stack don't seem to work.

For other charts like bar the code

backGroundColor: ["red"]

on the datasets object works fine but if I try to do the same for a line chart it doesn't. The top label icon that you click to hide or show the chart is the only one that seems to respond to the background color change. The area below the line doesn't. Please help.

<Line data={data} options={options} />
Insufferable answered 21/4, 2022 at 8:40 Comment(1)
Could you please add a minimal reproducible example and the desired outcome?Annals
L
13

You need to set fill to true in your dataset. And depending on if you are using treeshaking you also will need to import and register filler from chart.js.

  const data = {
    labels: ["1 Dec", "8 Dec", "16 Dec", "31 Dec"],
    datasets: [
      {
        label: "Sales Made",
        data: [3, 7, 4, 5],
        borderColor: ["#03A9F5"],
        fill: true,
        backgroundColor: 'pink'
      },
    ],
  };
Lacking answered 21/4, 2022 at 9:25 Comment(2)
Thanks this just worked. Is there any way I can use a gradient in the color? like instead of pink. to have like a pinkish gradient with maybe some opacity?.Insufferable
Yes, you can just pass a canvas gradient to it: https://mcmap.net/q/1145250/-how-to-create-a-gradient-fill-line-chart-in-latest-chart-js-version-3-3-2Lacking

© 2022 - 2024 — McMap. All rights reserved.