[javascript] 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?

See fiddle: Jsfidle

HTML

<div class="graph">
  <div class="chart-legend">

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

JavaScript

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
                }
            }]
        }
    }
});

This question is related to javascript jquery chart.js

The answer is


Needed the chart to fill the parent element 100%, rather than setting height manually, and the problem was to force parent div to always fill remaining space.

After setting responsive and ratio options (check out related chartjs doc), the following css did the trick:

html

<div class="panel">
  <div class="chart-container">
    <canvas id="chart"></canvas>
  </div>
</div>

scss:

.panel {
  display: flex;

  .chart-container {
    position: relative;
    flex-grow: 1;
    min-height: 0;
  }
}

You should use html height attribute for the canvas element as:

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

This one worked for me:

I set the height from HTML

canvas#scoreLineToAll.ct-chart.tab-pane.active[height="200"]
canvas#scoreLineTo3Months.ct-chart.tab-pane[height="200"]
canvas#scoreLineToYear.ct-chart.tab-pane[height="200"]

Then I disabled to maintaining aspect ratio

options: {
  responsive: true,
  maintainAspectRatio: false,

I created a container and set it the desired height of the view port (depending on the number of charts or chart specific sizes):

.graph-container {
width: 100%;
height: 30vh;
}

To be dynamic to screen sizes I set the container as follows:

*Small media devices specific styles*/
@media screen and (max-width: 800px) {
.graph-container {
        display: block;
        float: none;
        width: 100%;
        margin-top: 0px;
        margin-right:0px;
        margin-left:0px;
        height: auto;
    }
}

Of course very important (as have been referred to numerous times) set the following option properties of your chart:

options:{
    maintainAspectRatio: false,
    responsive: true,
}

If you disable the maintain aspect ratio in options then it uses the available height:

var chart = new Chart('blabla', {
                type: 'bar',
                data: {
                },
                options: {
                    maintainAspectRatio: false,
                }
            });

Just to add on to the answer given by @numediaweb

In case you're banging your head against the wall because after following the instructions to set maintainAspectRatio=false: I originally copied my code from an example I got on a website on using Chart.js with Angular 2+:

        <div style="display: block">
          <canvas baseChart
                  [datasets]="chartData"
                  [labels]="chartLabels"
                  [options]="chartOptions"
                  [legend]="chartLegend"
                  [colors]="chartColors"
                  [chartType]="chartType">
          </canvas>
        </div>

To make this work correctly you must remove the embedded (and unnecessary) style="display: block" Instead define a class for the enclosing div, and define its height in CSS.

Once you do that, the chart should have responsive width but fixed height.


Set the aspectRatio property of the chart to 0 did the trick for me...

    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
                    }
                }]
            }
        }
    });
myChart.aspectRatio = 0;

The easiest way is to create a container for the canvas and set its height:

<div style="height: 300px">
  <canvas id="chart"></canvas>
</div>

and set

options: {  
    responsive: true,
    maintainAspectRatio: false
}

You can also set the dimensions to the canvas

<canvas id="myChart" width="400" height="400"></canvas>

And then set the responsive options to false to always maintain the chart at the size specified.

options: {
    responsive: false,
}

He's right. If you want to stay with jQuery you could do this

var ctx = $('#myChart')[0];
ctx.height = 500;

or

var ctx = $('#myChart');
ctx.attr('height',500);

You can wrap your canvas element in a parent div, relatively positioned, then give that div the height you want, setting maintainAspectRatio: false in your options

//HTML
<div id="canvasWrapper" style="position: relative; height: 80vh/500px/whatever">
<canvas id="chart"></canvas>
</div>

<script>
new Chart(somechart, {
options: {
    responsive: true,
    maintainAspectRatio: false

/*, your other options*/

}
});
</script>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to chart.js

Set height of chart in Chart.js how to set start value as "0" in chartjs? Setting width and height Chart.js v2 hide dataset labels How to format x-axis time scale values in Chart.js v2 How to set ChartJS Y axis title? how to display data values on Chart.js How to set max and min value for Y axis JavaScript Chart.js - Custom data formatting to display on tooltip In Chart.js set chart title, name of x axis and y axis?