[Chartjs]-How to set vertical lines for new day on x-axis in ChartJS v3.x

2๐Ÿ‘

โœ…

You could use the annotation plugin. In your case you will need to change the string I used to determine the correct x axis placement to the timestamp of the midnight you want and then you have a line there:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'pink'
    }]
  },
  options: {
    plugins: {
      annotation: {
        annotations: {
          line1: {
            type: 'line',
            xMin: 'Green',
            xMax: 'Green',
            label: {
              enabled: true,
              content: 'end value'
            }
          },
          line2: {
            type: 'line',
            xMin: 'Blue',
            xMax: 'Blue',
            label: {
              enabled: true,
              content: 'begin value'
            }
          }
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.3.1/chartjs-plugin-annotation.min.js"></script>
</body>

1๐Ÿ‘

You can use a mixed chart to create this graph mixing a line chart and a bar chart.

Here you can view one example:

https://codepen.io/alyf-mendonca/pen/dyZZoeB

HTML:


    <div>
      <canvas id="myChart"></canvas>
    </div>
    
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

JS:


    const labels = [
            'January',
            'February',
            'March',
            'April',
            'May',
            'June',
        ];
    
        const data = {
      labels: [
        '20:00',
        '21:00',
        '22:00',
        '23:00',
        '00:00',
        '01:00',
        '02:00'
      ],
      datasets: [{
        type: 'line',
        label: 'Bar Dataset',
        data: [20, 21, 23, 22, 21, 20, 23],
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgba(255, 99, 132, 0.2)'
      }, {
        type: 'bar',
        label: 'Line Dataset',
        data: [0, 0, 0, 0, 50, 0, 0],
        fill: false,
        borderColor: 'rgb(54, 162, 235)'
      }]
    };
    
        const config = {
            type: 'bar',
            data: data,
            options: {
                scales: {
                    x: {
                        stacked: true
                    }
                }
            },
        };
      
    
    const myChart = new Chart(
          document.getElementById('myChart'),
          config
        );

Leave a comment