react-chartjs-2如何在折线图中设置多个背景水平 [英] react-chartjs-2 how to set multiple background levels within a line chart

查看:245
本文介绍了react-chartjs-2如何在折线图中设置多个背景水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组数据,这些数据将显示在折线图中。 X轴将具有天,Y轴将具有0-200的值。

I have a set of data which will be displayed in a line chart. The X axis will have "days", Y axis will have values from 0 - 200.

我希望图表背景的值在80以下时为黄色 ,绿色表示80-120之间的值,红色表示大于120的值。

I want the background of the chart to be "yellow" for values under 80, and "green" for values between 80-120, "red" for values higher than 120.

我正在阅读文档,但找不到内容类似的,我包括了一张图片。
非常感谢。

I've being reading the documentation but I couldn't find something similar, i've included a picture of how it should be. Many thanks.

推荐答案

您可以使用 chartjs-plugin-annotation 并绘制单个彩色框,如下面的可运行代码段所示。

You can use chartjs-plugin-annotation and draw individual colored boxes as shown in the runnable code snippet below.

new Chart('chart', {
  type: 'line',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
    datasets: [{
      label: 'My Dataset',
      data: [60, 90, 130, 110, 100, 90, 80, 70, 80, 100],
      backgroundColor: 'rgba(0, 0, 0, 0.2)',
      borderColor: 'rgb(0, 0, 0)',
      borderWidth: 1,
      fill: false
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          stepSize: 20
        },
        gridLines: {
          display: false
        }
      }],
      xAxes: [{
        gridLines: {
          display: false
        },
      }]
    },
    annotation: {
      annotations: [{
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin: 120,
        yMax: 220,
        borderColor: 'rgba(255, 51, 51, 0.25)',
        borderWidth: 0,
        backgroundColor: 'rgba(255, 51, 51, 0.25)',
      },
      {
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin: 80,
        yMax: 120,
        borderColor: 'rgba(0, 204, 0, 0.25)',
        borderWidth: 0,
        backgroundColor: 'rgba(0, 204, 0, 0.25)',
      },
      {
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin: 0,
        yMax: 80,
        borderColor: 'rgba(255, 255, 0, 0.25)',
        borderWidth: 0,
        backgroundColor: 'rgba(255, 255, 0, 0.25)',
      }],
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
<canvas id="chart" height="80"></canvas>

这篇关于react-chartjs-2如何在折线图中设置多个背景水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆