Chartjs-Change horizontal line chart to vertical line

0👍

You need to adjust your data, you still provide your data as if your x axis is the index axis.

To solve your issue change the x and y keys in your data object and it will work fine:

data: [{
    y: '2022-03-01',
    x: 3
  },
  {
    y: '2022-03-02',
    x: 6
  },
  {
    y: '2022-03-03',
    x: 9
  },
  {
    y: '2022-03-04',
    x: 8
  }
],

Live sample:

const data = {
  datasets: [{
      label: 'PZ-1',
      data: [{
          y: '2022-03-01',
          x: 3
        },
        {
          y: '2022-03-02',
          x: 6
        },
        {
          y: '2022-03-03',
          x: 9
        },
        {
          y: '2022-03-04',
          x: 8
        }
      ],
      backgroundColor: [
        'rgba(255, 26, 104, 0.2)'
      ],
      borderColor: [
        'rgba(255, 26, 104, 1)'
      ],
      borderWidth: 1
    },
    {
      label: 'PZ-2',
      data: [{
          y: '2022-03-03',
          x: 10
        },
        {
          y: '2022-03-04',
          x: 12
        },
        {
          y: '2022-03-05',
          x: 13
        },
        {
          y: '2022-03-06',
          x: 10
        }
      ],
      backgroundColor: [
        'rgba(255, 26, 104, 0.2)'
      ],
      borderColor: [
        'rgba(255, 26, 104, 1)'
      ],
      borderWidth: 1
    },
  ]
};
// config 
const config = {
  type: 'line',
  data,
  options: {
    indexAxis: 'y',
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
};
// render init block
const myChart = new Chart(
  document.getElementById('myChart'),
  config
);
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Line Chart</title>
</head>

<body>
  <div class="chartCard">
    <div class="chartBox">
      <canvas id="myChart"></canvas>
    </div>
  </div>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
</body>

</html>

Leave a comment