如何在折线图上使用填充颜色添加带有折线的区域

时间:2019-05-19 15:22:18

标签: javascript charts chart.js linechart chartist.js

我需要显示一个折线图,其中单个数据集具有区域分隔符。 在单个数据集上,区域将分为不同的填充颜色。如图所示。

enter image description here

1 个答案:

答案 0 :(得分:1)

下面是一个代码段,该代码段基于{0}在y轴上基于值'0'适应了仅previous answer的情况。

此版本在x轴上有效,并以标签值的数组(ranges)作为起点和终点来设置渐变色标。

let ranges = [
    ['2019-01-02', '2019-01-03'],
    ['2019-01-06', '2019-01-09']
  ],
  posColour = 'rgba(0, 255, 0, .1)',
  negColour = 'rgba(255, 0, 0, .1)',
  myBarChart = new Chart(document.getElementById('chart'), {
    type: 'line',
    data: {
      labels: ['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10'],
      datasets: [{
        label: 'Series1',
        data: [1, 10, 6, 9, 3, 6, 4, 5, 8, 10]
      }]
    },
    options: {
      maintainAspectRatio: false,
      scales: {
        xAxes: [{
          type: 'time',
          time: {
            unit: 'day'
          }
        }]
      }
    },
    plugins: [{
      beforeRender: function(c, options) {
        let dataset = c.data.datasets[0],
          x = c.scales['x-axis-0'],
          fill = c.ctx.createLinearGradient(0, 0, c.width, 0),
          model = dataset._meta[Object.keys(dataset._meta)[0]].$filler.el._model;

        fill.addColorStop(0, posColour);
        for (let i = 0, ii = ranges.length; i < ii; i++) {
          xPos1 = x.getPixelForValue(ranges[i][0]);
          xPos2 = x.getPixelForValue(ranges[i][1]);

          fill.addColorStop(xPos1 / c.width, posColour);
          fill.addColorStop(xPos1 / c.width, negColour);
          fill.addColorStop(xPos2 / c.width, negColour);
          fill.addColorStop(xPos2 / c.width, posColour);
        }
        fill.addColorStop(1, posColour);
        model.backgroundColor = fill;
      }
    }]
  });
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="chart"></canvas>

相关问题