Search code examples
javascriptjquerychart.js

Set height of chart in Chart.js


I want to draw a horizontal bar chart with Chart.js but it keeps scaling the chart instead of using the height I assign the canvas form the script.

Is there any way to set the height of the graph from the script?

var ctx = $('#myChart');

ctx.height(500);

var myChart = new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  maintainAspectRatio: false,
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<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.4.0/Chart.min.js"></script>
<div class="graph">
  <div class="chart-legend">

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

See code on fiddle: Jsfiddle


Solution

  • Seems like var ctx = $('#myChart'); is returning a list of elements. You would need to reference the first by using ctx[0]. Also height is a property, not a function.

    I did it this way in my code:

    var chartEl = document.getElementById("myChart");
    chartEl.height = 500;