[Chartjs]-Chart.js Bar Chart with a switch/radio button to group data / Troubleshooting bar color

3👍

it works about like this …

var chart = null;

var chartData = {
  labels: ['Question 1', 'Question 2'],
  datasets: [
    {label: 'yes', backgroundColor: '#004831', data: [714, 233]},
    {label: 'no', backgroundColor: '#76B900', data: [800, 451]}
  ]
};

var chartOptions = {
  tooltips: {mode: 'index', intersect: true},
  legend: {display: false},
  responsive: true,
  scales: {
    xAxes: [{
      ticks: {beginAtZero: true},
      stacked: true
    }],
    yAxes: [{
      ticks: {beginAtZero: true},
      stacked: false
    }]
  }
};

$(function() {

  chart = new Chart($('#chart'), {
    type: 'bar',
    data: chartData,
    options: chartOptions
  });
  
  $("input#toggle[type='checkbox']").click(function (event) {
    var isStacked = false;
    if ($(this).is(':checked')) {
      isStacked = true;
    } else {
      isStacked = false;
    }
    
    chart.options.scales = {
      xAxes: [{ stacked: isStacked }],
      yAxes: [{ stacked: isStacked }]
    };
    chart.update();
  });
  
});
canvas {
   -moz-user-select: none;
   -webkit-user-select: none;
   -ms-user-select: none;
}
.toggle {
    position: relative;
    margin: 20px auto;
    width: 55px;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select: none;
}
.toggle-checkbox {
    display: none;
}
.toggle-label {
    display: block; overflow: hidden; cursor: pointer;
    height: 20px; padding: 0; line-height: 20px;
    border: 0px solid #FFFFFF; border-radius: 30px;
    background-color: #9E9E9E;
}
.toggle-label:before {
    content: "";
    display: block; width: 30px; margin: -5px;
    background: #FFFFFF;
    position: absolute; top: 0; bottom: 0;
    right: 31px;
    border-radius: 30px;
    box-shadow: 0 6px 12px 0px #757575;
}
.toggle-checkbox:checked + .onoffswitch-label {
    background-color: #42A5F5;
}
.toggle-checkbox:checked + .toggle-label, .toggle-checkbox:checked + .toggle-label:before {
   border-color: #42A5F5;
}
.toggle-checkbox:checked + .toggle-label .toggle-inner {
    margin-left: 0;
}
.toggle-checkbox:checked + .toggle-label:before {
    right: 0px; 
    background-color: #2196F3; 
    box-shadow: 3px 6px 18px 0px rgba(0, 0, 0, 0.2);
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<div class="toggle">
    <input id="toggle" type="checkbox" class="toggle-checkbox"/>
    <label for="toggle" class="toggle-label">&nbsp;</label>
</div>
<canvas id="chart" width="100%" height="100%"></canvas>

here’s the docs.

Leave a comment