John Wyant
John Wyant

Reputation: 83

Stacked Bar Chart, Two on Same Line w/ Same Color

Good afternoon!

I need to have a horizontal bar chart where I can have stacked data, as shown in the picture. The data is potentially stacked and the stacked then needs to have the same color as everything else in the bar.

I get the right look, but when you hover, it shows a bunch of [NaN, NaN].

Sample of how I'm getting it: https://jsfiddle.net/3s5mchp1/1/

<head>
    <title>Floating Bars</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
    <style>
        canvas {
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
        }
    </style>
</head>

<body>
    <div>
        <canvas id="canvas" height="100"></canvas>
    </div>
    <script>         
      window.onload = function() {
         var ctx = document.getElementById('canvas').getContext('2d');
         window.myBar = new Chart(ctx, {
            type: 'horizontalBar',
            data:{
               labels:[1, 2],
               datasets:[
               {
                 label:'data',
                 data:[[-3, 5]],
                 backgroundColor: 'lightblue'
               },
               {
                 label:'data',
                 data:[[], [6,8]],
                 backgroundColor: 'orange'
               },
               {
                 label:'data',
                 data:[[10, 11]],
                 backgroundColor: 'lightblue'
               }
               ]
            },
            options: {
               responsive: true,
               scales: {
                xAxes: [{
                  stacked : false,

                 }],
                 yAxes: [{
                  stacked : true,

                 }]
               },
               legend: {
                 position: 'top',
               },
               title: {
                 display: true,
                 text: 'Horizontal Floating Bars'
               }
            }
         });
      };
    </script>
</body>
</html>

enter image description here

Upvotes: 0

Views: 284

Answers (1)

Sdamico
Sdamico

Reputation: 66

A quick way to remedy this is to add a tooltip callback to your chart:

jsfiddle

tooltips: {
     callbacks: {
      label: function(tooltipItems, data) {
        if (isNaN(tooltipItems.x)) return null
        return tooltipItems.xLabel
      }
   }
}

Upvotes: 1

Related Questions