Gradient color for each bar in a histogram using ChartJS

I am trying to create a bar chart using ChartJS that will look like this:

enter image description here

I want to know how to add a gradient color for each columns separately and according to their heights.

I found a very close solution here , but it sets createLinearGradient

for the whole chart, not individual bars.

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

Is there a way to specify stopPoints

according to the column height and not the element coordinates <canvas />

?

Or maybe a way to calculate the coordinates of the plot according to a certain column height?

Thank you in advance:)

+3


source to share


1 answer


To get an effect similar to the provided image, you can use stacked histograms with three datasets. Take a look at the code cut 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>
      

Run codeHide result


0


source







All Articles