使用ChartJS的条形图中每个条的渐变颜色 [英] Gradient color for each bar in a bar graph using ChartJS

查看:350
本文介绍了使用ChartJS的条形图中每个条的渐变颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用ChartJS创建一个条形图,它看起来像这样:

p>

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



我发现了一个非常接近的解决方案这里,但是它为整个图表设置了 createLinearGradient ,而不是针对单个条。



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

有没有办法规范ify stopPoints 根据栏高度而不是坐标在< canvas /> 元素上?



或者也许是根据特定的酒吧高度计算图表坐标的方法?



谢谢为了得到一个看起来像在你提供的示例图像中的效果,你可以使用堆叠的条形图有三个数据集。看看代码片段,看看我的意思。



var bar_ctx = bar.ctx,{type:'bar',data:{labels:[1,2,3);数据集:[{标签:'test0',数据:[3,4,7,3,6,2],backgroundColor:'deepskyblue',},{4,5,6, 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 =条形图><<< ; / canvas>


I'm trying to create a bar graph using ChartJS, which will look like this:

I want to know how can I add gradient color for each of the bars separately, and according to their heights.

I found a very close solution here, but it sets the createLinearGradient for the whole graph, not for individual bars.

Also, this solution is more closer, if I create gradients for each bars, but then, I want to set gradients according to the bars height.

Is there a way to specify stopPoints according to the bar height, and not coordinates on the <canvas /> element?

Or maybe a way to calculate graph coordinates according to a specific bar height?

Thanks in advance :)

解决方案

In order to get an effect that looks like in your provided sample image you could use a stacked bar charts with three datasets. Have a look at the code snipped to see what I mean.

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>

这篇关于使用ChartJS的条形图中每个条的渐变颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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