使用ChartJS在条形图中每个条形的渐变颜色

时间:2017-04-26 09:59:20

标签: graph charts chart.js

我正在尝试使用ChartJS创建条形图,如下所示:

enter image description here

我想知道如何根据高度为每个分别为添加渐变颜色。

我找到了一个非常接近的解决方案here,但它为整个图表设置了createLinearGradient,而不是针对单个条形图。

另外,this解决方案更接近,如果我为每个条形创建渐变,但是,我想根据条形高度设置渐变。

有没有办法根据条形高度指定stopPoints,而不是<canvas />元素上的坐标?

或者根据特定的条形高度计算图形坐标的方法?

提前致谢:)

1 个答案:

答案 0 :(得分:0)

为了获得与您提供的样本图像类似的效果,您可以使用带有三个数据集的堆积条形图。看看代码剪断,看看我的意思。

var bar_ctx = document.getElementById('bar-chart').getContext('2d');

var bar_chart = new Chart(bar_ctx, {
  type: 'bar',
  data: {
    labels: ["1", "2", "3", "4", "5", "6"],
    datasets: [{
        label: 'test0',
        data: [3, 4, 7, 3, 6, 2],
        backgroundColor: 'deepskyblue',
      }, {
        label: 'test1',
        data: [2, 9, 3, 3, 4, 8],
        backgroundColor: 'skyblue'
      },
      {
        label: 'test2',
        data: [2, 9, 3, 3, 4, 8],
        backgroundColor: 'powderblue'
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        stacked: true,
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js"></script>

<canvas id="bar-chart"></canvas>

相关问题