Search code examples
chart.js

How to make datasets' line always appear on top of other datasets' background on a line chart in ChartJS?


I have a line chart with 2 datasets that overlap. Each dataset has background and a line color.
I want to make all datasets lines (borders) appear on top of all backgrounds. And making the background semi-transparent is not the solution I'm looking for. (Currently the blue dataset background is displayed above the red dataset line)

  const ctx = document.getElementById("chart")

  new Chart(ctx, {
    type: "line",
    data: {
      labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"],
      datasets: [
        {
          label: "First Dataset",
          data: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
          fill: true,
          borderColor: "blue",
          backgroundColor: "blue",
        },
        {
          label: "Second Dataset",
          data: [100, 90, 80, 70, 60, 50, 40, 30, 20, 10],
          fill: true,
          borderColor: "red",
          backgroundColor: "red",
        }
      ]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  })
<div>
  <canvas id="chart"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


Solution

  • You have to set the drawTime of the filler plugin at beforeDraw or, better, beforeDatsetsDraw, see the docs.

    This means that all fill operations are performed before anything else is drawn (beforeDraw), or after other layers are drawn, like axes or legend boxes, but before any of the datasets are drawn (beforeDatasetsDraw). The default value is beforeDatasetDraw, performing each dataset fill operation before the rest of its drawing, but after the datasets that come before it are drawn.

    Your snippet with this addition:

    const ctx = document.getElementById("chart")
    
      new Chart(ctx, {
        type: "line",
        data: {
          labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"],
          datasets: [
            {
              label: "First Dataset",
              data: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
              fill: true,
              borderColor: "blue",
              backgroundColor: "blue",
            },
            {
              label: "Second Dataset",
              data: [100, 90, 80, 70, 60, 50, 40, 30, 20, 10],
              fill: true,
              borderColor: "red",
              backgroundColor: "red",
            }
          ]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          },
          plugins:{
             filler:{
                drawTime: "beforeDatasetsDraw"
             }
          }
        }
      })
    <div>
      <canvas id="chart"></canvas>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>