Home > Mobile >  ChartJS - Labels background
ChartJS - Labels background

Time:12-15

I am using Chart.js to draw a simple line chart. How can I make background color in the area of XAxis Labels and YAxis Labels?

The documentation for Line Chart is here: https://www.chartjs.org/docs/2.7.3/getting-started/?h=line, but I can't find anything about it.

This is the areas I want to apply background color: ChartJS area

Thanks in advance.

CodePudding user response:

You can use the build in backgroundColor on the scale, this approach only colors the part under the chartArea:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    scales: {
      y: {
        backgroundColor: 'red'
      },
      x: {
        backgroundColor: 'yellow'
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>

If you really want all the length you will need to write a custom plugin:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      scaleBackground: {
        x: 'red',
        y: 'yellow',
        drawXOverY: true
      }
    }
  },
  plugins: [{
    id: 'scaleBackground',
    beforeDraw: (chart, args, opts) => {
      const {
        scales: {
          x,
          y
        },
        ctx,
        chartArea: {
          left
        },
        canvas
      } = chart;

      if (opts.drawXOverY) {
        ctx.fillStyle = opts.y || 'transparent';
        ctx.fillRect(0, 0, left, canvas.height);

        ctx.fillStyle = opts.x || 'transparent';
        ctx.fillRect(0, x.top, canvas.width, x.bottom);
      } else {
        ctx.fillStyle = opts.x || 'transparent';
        ctx.fillRect(0, x.top, canvas.width, x.bottom);

        ctx.fillStyle = opts.y || 'transparent';
        ctx.fillRect(0, 0, left, canvas.height);
      }


    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>

  • Related