图表 js y 轴的不同背景

2022-01-22 00:00:00 graph javascript css chart.js

I have a line chart in chart js. I want to give it a different background on the y axis say, 0-40 is red,40-70 is yellow and 70-100 is green. The limit for the y axis will always be 100.

   var scatterChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [{
            label: ' Dataset',
            data: [{
                x: 1,
                y: 10
            }, {
                x: 2,
                y: 50
            }, {
                x: 3,
                y: 88
            }, {
                x: 4,
                y: 5
            }]
        }]
    },
    options: {
        scales: {
            xAxes: [{
                type: 'linear',
                position: 'bottom'
            }]
        }
    }
});

How do i set the background?

解决方案

There is not a built in option, but we can achieve the result with some code.

var ctx = document.getElementById("chart").getContext("2d");

var scatterChart = new Chart(ctx, {
  type: "line",
  data: {
    datasets: [{
      label: " Dataset",
      data: [{
          x: 1,
          y: 10
        },
        {
          x: 2,
          y: 50
        },
        {
          x: 3,
          y: 88
        },
        {
          x: 4,
          y: 5
        }
      ]
    }]
  },
  options: {
    backgroundRules: [{
        backgroundColor: "red",
        yAxisSegement: 40
      },
      {
        backgroundColor: "yellow",
        yAxisSegement: 70
      },
      {
        backgroundColor: "green",
        yAxisSegement: Infinity
      }
    ],
    scales: {
      xAxes: [{
        type: "linear",
        position: "bottom"
      }],
      yAxes: [{
        color: ["#123456", "#234567"]
      }]
    }
  },
  plugins: [{
    beforeDraw: function(chart) {
      var ctx = chart.chart.ctx;
      var ruleIndex = 0;
      var rules = chart.chart.options.backgroundRules;
      var yaxis = chart.chart.scales["y-axis-0"];
      var xaxis = chart.chart.scales["x-axis-0"];
      var partPercentage = 1 / (yaxis.ticksAsNumbers.length - 1);
      for (var i = yaxis.ticksAsNumbers.length - 1; i > 0; i--) {
        if (yaxis.ticksAsNumbers[i] < rules[ruleIndex].yAxisSegement) {
          ctx.fillStyle = rules[ruleIndex].backgroundColor;
          ctx.fillRect(xaxis.left, yaxis.top + (i - 1) * (yaxis.height * partPercentage), xaxis.width, yaxis.height * partPercentage);
        } else {
          ruleIndex++;
          i++;
        }
      }
    }
  }]
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<div class="container">
  <canvas id="chart"></canvas>
</div>

相关文章