score:5

Accepted answer

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.

score: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>


Related Query

More Query from same tag