[Chartjs]-Chart.js set one bar as different colour?

5👍

You can change the color of a bar element after you have created your chart.

After new Chart() statement you can access and modify the chart element properties and update the chart like this :

var wpChartChartTitleBar = new Chart(document.getElementById("myChart").getContext("2d")).Bar(ChartTitleData, ChartTitleOps);

// Change 2nd bar to red (display).
wpChartChartTitleBar.datasets[0].bars[1].fillColor = "rgba(229,12,12,0.7)";
wpChartChartTitleBar.datasets[0].bars[1].strokeColor = "rgba(229,12,12,1)";

// Change 2nd bar to red (highlight setting on mouse over)
wpChartChartTitleBar.datasets[0].bars[1].highlightFill = "rgba(0,229,0,0.7)";
wpChartChartTitleBar.datasets[0].bars[1].highlightStroke = "rgba(0,229,0,1)";

wpChartChartTitleBar.update();

See a fiddle of it here.

4👍

Since rtome’s method doesn’t seem to work in newer versions of Chart.js, here’s a working example of differing bar colours for the current version (2.9.3 as of this post).

var ctx = document.getElementById("myChart").getContext("2d");
var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: "horizontalBar",

  // The data for our dataset
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First dataset",
      backgroundColor: [
        "rgb(255, 99, 132)",
        "rgb(255, 159, 64)",
        "rgb(255, 205, 86)",
        "rgb(75, 192, 192)",
        "rgb(54, 162, 235)",
        "rgb(153, 102, 255)",
        "rgb(201, 203, 207)"
      ],
      borderColor: "rgb(255, 99, 132)",
      data: [3, 10, 5, 2, 20, 30, 45]
    }]
  },

  // Configuration options go here
  options: {}
});
canvas {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}

body {
  margin-top: 35px;
}

#container {
  width: 95%;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
}
<html>

<head>
  <title>Bar colour example</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
</head>

<body>
  <div id="container">
    <canvas id="myChart"></canvas>
  </div>
</body>

</html>

Leave a comment