Horizontal line for bar chart

32 views Asked by At

Information: Chart.js v3.8.2 https://www.chartjs.org

new Chart(document.getElementById('esneklik').getContext('2d'), {
type: 'bar',
data: {
    labels: ['test','test 2'],
    datasets: [{
        label: ' ',
        data: [24,20],
        backgroundColor: ['rgba(1, 56, 108, 0.6)'],
        borderColor: ['rgba(1, 56, 108, 1'],
        borderWidth: 1
    }]
},
options: {
    scales: {
        y: {
            beginAtZero: true,
            type: 'linear',
            min: 5,
            max: 50
        }
    }
}
});

Example: enter image description here

I want to draw a line horizontally and show the average value.

1

There are 1 answers

0
WhiteHat On

you can add a second dataset for the line.

specify the type as 'line' and set fill to false

      datasets: [{
          type: 'line',  // <-- type as line
          label: 'avg',
          data: [22,22],
          fill: false,   // <-- fill as false
          backgroundColor: 'red',
          borderColor: 'red',
          borderWidth: 1
      }, {
          label: 'bar',
          data: [24,20],
          backgroundColor: 'rgba(1, 56, 108, 0.6)',
          borderColor: 'rgba(1, 56, 108, 1)',
          borderWidth: 1
      }]

the line dataset should be added first, else it will be behind the bars

see following working snippet...

$(document).ready(function() {
    new Chart(document.getElementById('esneklik').getContext('2d'), {
      type: 'bar',
      data: {
          labels: ['test','test 2'],
          datasets: [{
              type: 'line',
              label: 'avg',
              data: [22,22],
              fill: false,
              backgroundColor: 'red',
              borderColor: 'red',
              borderWidth: 1
          }, {
              label: 'bar',
              data: [24,20],
              backgroundColor: 'rgba(1, 56, 108, 0.6)',
              borderColor: 'rgba(1, 56, 108, 1)',
              borderWidth: 1
          }]
      },
      options: {
          scales: {
              yAxes: [{
                  beginAtZero: true,
                  type: 'linear',
                  ticks: {
                    min: 5,
                    max: 50
                  }
              }]
          }
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="esneklik"></canvas>