[Chartjs]-How to show group by data just like sample image using Chart.js?

1👍

You can add a second x axis that shows the date and empty labels for the other spaces, then you can use null values in your data array to make the data points appear in the right spots.

Example:

<!DOCTYPE html>
<html>

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chart.js Mixed Chart</title>
  <!--Chart.js JS CDN-->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</head>

<body>

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

  <script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ["PM", "AM", "Night", "PM", "AM", "Night"],
        datasets: [{
            data: [null, 49, null, null, 51],
            label: "AM",
            borderColor: "#3e95cd",
            backgroundColor: "rgb(62,149,205)",
            borderWidth: 2,
            type: 'line',
            fill: false,
            showLine: false
          }, {
            data: [47, null, null, 48],
            label: "PM",
            borderColor: "#3cba9f",
            backgroundColor: "#3cba9f",
            borderWidth: 2,
            showLine: false
          }, {
            data: [null, null, 50, null, null, 52],
            label: "Night",
            borderColor: "#ffa500",
            backgroundColor: "#ffa500",
            borderWidth: 2,
            showLine: false
          }

        ]
      },
      options: {
        scales: {
          xAxes: [{},
            {
              id: 'dates',
              type: 'category',
              position: 'bottom',
              labels: ["", "05/05/2021", "", "", "06/05/2021", ""]
            }
          ]
        }
      }

    });
  </script>

</body>

</html>

Fiddle: https://jsfiddle.net/Leelenaleee/4tx2swmr/1/

Leave a comment