[Chartjs]-Horizontal floating bars with a time y-axis in Chart.js

1๐Ÿ‘

โœ…

Mmm it seems my issues are:

  • not using proper axis format for chart.js 3
  • need to scale the graph myself
  • need to refer to horizontal axis as x
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
</head>

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

<script>

//const labels = ["a","b","c","d","fff","g","h"]
const labels = ["a","b"]
const data = {
  labels: labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: [[("2021-11-23T00:24:14Z"),("2021-11-23T00:34:03Z")],
          [("2021-11-23T00:25:14Z"),("2021-11-23T00:26:35Z")]]
      // This works fine (without 'yAxes' below):
      //data: labels.map(() => {
        //return [Math.random(), Math.random()];
      //}),
      //backgroundColor: Utils.CHART_COLORS.red,
    },

  ]
};
const config = {
  type: 'bar',
  data: data,
  options: {
      scales: {
          x: {
              min: ("2021-11-23T00:20:14Z"), 
              max: ("2021-11-23T00:44:14Z") ,
            type: 'time',
          },
      },
      indexAxis: 'y',
      responsive: true,
      plugins: {
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: 'Chart.js Floating Bar Chart'
        }
      }
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);

</script>
</html>

0๐Ÿ‘

Thanks for the idea @jberryman. I adopted it and build this on top:

<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
</head>

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

<script>

const data = {
  labels: [''],
  datasets: [
    { data: [[8,9]], backgroundColor: 'green' },
    { data: [[12, 14]], backgroundColor: 'green'},
        { data: [[7, 16]], backgroundColor: 'lightgrey'}
  ]
};
const config = {
  type: 'bar',
  data: data,
  options: {
      scales: {
          y: {
                stacked: true,
            },
          x: {
            min: 0, 
            max: 24 ,
            ticks: {
                stepSize: 2
            }
          },
      },
      indexAxis: 'y',
      responsive: true,
      plugins: {
        legend: false,
        title: false
      }
  }
};

var ctx = document.getElementById("myChart");
new Chart(ctx, config);

</script>
</html>

see https://jsfiddle.net/h9vk5sfx/46/

Leave a comment