[Chartjs]-How to use Chartjs to plot a single row of colored bars with a time based x axis

1👍

Well your code basically works, here a slightly modified version of your code.

After your comments and updated question, I reworke the example (seen below). Although it is possible to do with chart.js the question is, maybe for this specific task a different library or solution would be better/more convenient.

Update Chart, with some similar values from your question:
(I’m using here momentjs, since it is recommend usually needed form date/time actions in chartjs, as mentioned in the documentation)

const d0 = moment.duration('07:00:00').asMinutes();
const d1 = moment.duration('09:00:00').asMinutes();
const d2 = moment.duration('10:45:00').asMinutes();
const d3 = moment.duration('17:35:00').asMinutes();
const d4 = moment.duration('19:00:00').asMinutes();
let values = [d0, d1, d2, d3, d4];

let data = {
    labels: [''],
    datasets: [{
      label: 'up',
      axis: 'y',
      data: [d1],
      backgroundColor: 'red',
    },{
      label: 'down',
      axis: 'y',
      data: [d2],
      backgroundColor: 'yellow',
    },{
      label: 'out',
      axis: 'y',
      data: [d3],
      backgroundColor: 'green',
    },{
      label: 'up',
      axis: 'y',
      data: [d4],
      backgroundColor: 'red',
    }
  ]
  };

const config = {
data,
type: 'bar',
    options:{
      plugins: {
        tooltip: {
           mode: 'dataset',
           callbacks: {
            label: function(item){
               return moment().startOf('day').add({ minute: item.raw}).format('HH:mm');
            }
          }
        },
        legend: {
          display: false,
        },
        title: {
          display: false,
        },
    },
    indexAxis: 'y',
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: {
        min: d0,
        ticks: {
            callback: function(value, index, ticks) {
                return moment().startOf('day').add({ minute: value}).format('HH:mm');
            }
        },
        afterBuildTicks: axis => axis.ticks = values.map(v => ({ value: v }))
      },
      y: {
        stacked: true
      },
    }
  }};
  
  new Chart(document.getElementById("chart"), config);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>    
<script src="//cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="//cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>   
<div class="chart" style="height:184px; width:350px;">
    <canvas  id="chart" ></canvas>
</div>

Leave a comment