272

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

Nickofthyme
  • 3,032
  • 23
  • 40
Vincent T
  • 3,044
  • 2
  • 9
  • 18
  • You may update the ratio height vs width of your chart with this solution https://stackoverflow.com/questions/40594025/chart-js-aspect-ratio-forced-height/67540672#67540672 – Sylhare May 14 '21 at 20:54
  • maybe relevant: https://github.com/chartjs/Chart.js/issues/3384 `Is it possible to make charts a fixed height? #3384 ` – nmz787 Jul 19 '22 at 02:19

18 Answers18

598

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,
    }
});
Ahmad Khan
  • 2,655
  • 19
  • 25
numediaweb
  • 16,362
  • 12
  • 74
  • 110
  • Yeaahh! It's working fine. Thanks for this tip. Best regards man. – Sedat Kumcu May 25 '17 at 14:10
  • 35
    Whay isn't this the accepted answer? Works perfectly – Tom Doodler Jul 28 '17 at 12:04
  • 5
    Interestingly, if you `destroy()` the chart and then create it again on the same canvas second time the height of the canvas may be messed up after destroying and has to be reapplied before creation. Though, you can avoid destroying and use `update` method instead, if you don't change options. – Gherman Oct 16 '17 at 08:30
  • 5
    How do I make it use available height but also set a min height? – Zapnologica Feb 14 '18 at 06:28
  • 1
    Would make sense to explain a bit what disabling this property does (except for what is already discussed). – fgblomqvist Sep 19 '18 at 19:43
  • 1
    also disable `responsive` option if it is not disabled yet – Stefano Mtangoo Jun 17 '21 at 16:34
  • 1
    In my case, the downside of this solution is that you have to set the responsive property to false for it to work. @bibamann solution works well with responsive being true. – Alphy Gacheru Apr 10 '22 at 15:34
235

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
}
Dipesh Bajgain
  • 801
  • 1
  • 10
  • 26
bibamann
  • 2,469
  • 1
  • 11
  • 9
  • 30
    Thanks for this, the key here is to set `maintainAspectRatio` to `false` in the options of the graph, otherwise the `height` assigned via the `style` attribute won't actually take effect. – Ben Feb 25 '18 at 11:26
  • 2
    The suggestion of Ben is gold. – rubeonline Nov 15 '18 at 12:12
  • The default value for the `responsive` option is `true`. Details: https://www.chartjs.org/docs/latest/general/responsive.html#configuration-options – Dem Pilafian Dec 23 '18 at 06:40
  • 1
    Thanks for clarifying that the `height` property must be on a parent element and not on the canvas – Savage Jul 07 '19 at 18:28
  • this was the only answer that worked for me. the other answers did not work. thanks. – Nguai al Jan 17 '22 at 19:03
97

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;
taxilian
  • 14,229
  • 4
  • 34
  • 73
Riscie
  • 3,775
  • 1
  • 24
  • 31
26

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>
Geoff Kendall
  • 1,307
  • 12
  • 13
  • 1
    Based on documentation on the Chart.js website this appears to be the correct approach. – Ryan D Oct 31 '18 at 21:13
  • Chart container relative position is the only way to achieve responsive height apparently. Here is the relevant doc: https://www.chartjs.org/docs/2.7.2/general/responsive.html#important-note – Slion Mar 29 '22 at 09:35
16

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,
Shiva
  • 11,485
  • 2
  • 67
  • 84
12

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,
}
velval
  • 3,072
  • 36
  • 45
8

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,
}
Hmerman6006
  • 1,622
  • 1
  • 20
  • 45
6

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);
relief.melone
  • 3,042
  • 1
  • 28
  • 57
5

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

<div class="chart">
    <canvas id="myChart" height="100"></canvas>
</div>
Basharat Hussain
  • 209
  • 1
  • 3
  • 8
  • Even though many solutions state to update the size via canvas, this doesn't work for me. – Sade Jul 23 '21 at 12:08
  • I figured out what the issue was. If I use the above example and just add in your code above. My chart will not display. This line is incorrect... --> maintainAspectRatio: false, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } – Sade Jul 25 '21 at 14:21
  • You need to edit that line so that it is --> options: { maintainAspectRatio: false, responsive: true, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } – Sade Jul 25 '21 at 14:23
  • I also have a problem changing the width? html code--> – Sade Jul 25 '21 at 14:44
  • options: { maintainAspectRatio: false, responsive: true, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } Only height is changing. – Sade Jul 25 '21 at 14:44
  • This link https://www.chartjs.org/docs/3.0.2/configuration/responsive.html confirms the issue mentioned earlier. Changing canvas height and width doesnt resize the graph, until we set the correct parameters within the options namespace. Note refer to links example: maintainAspectRatio is a variable within options and not outside it, hence it wasnt display. – Sade Jul 25 '21 at 15:09
4

See, there is a mistake in the initializing statement. The maintainAspectRatio should come inside the options object as follows

...

options = {
   maintainAspectRatio: false,

 ...
}

...

Now, what you can do is set the height of the parent element of the chart, so here div .chart is the parent of div #myChart. So, specifying the height of div .chart should just work fine.

Consider the following code.

<div class="chart" style="height: 500px;">
   <canvas id="myChart"></canvas>
</div>

Change the height according to yourself, for me 500px just works fine ;)

Charitra Agarwal
  • 362
  • 1
  • 11
3

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;
Franz Kiermaier
  • 387
  • 3
  • 19
1

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.

Andrew
  • 199
  • 1
  • 14
1

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;
  }
}
Be Kind
  • 4,712
  • 1
  • 38
  • 45
0

Setting the Size of a chartjs diagram can be simply achieved by setting the with of a surrounding container:

   <div style="width:400px;">
     <canvas id="myChart"></canvas>
   </div>

But an important detail is, that you may need to resize your diagram after creation:

var ctx = $('#myChart');
var myChart = new Chart(ctx, {
    ......
    data: {
           ........
    },
    options: {
        responsive: false,
        maintainAspectRatio: true
    }
});
// now resize the new chart to fit into the canvas....
myChart.resize();
Ralph
  • 4,500
  • 9
  • 48
  • 87
0

The problem here is that maintainAspectRatio needs to be inside the options node, not at the same level as in the example.

0

Add one relative position element whose height is calculated from padding (works same as aspect ratio) but if you need that chart does not exceed certain maximum height then use new powerful min unit of css. Also add fixed fallback padding where this is not supported.

<div class="dashboard-charts" style="position: relative; padding-top:40%; padding-top:min(40%,530px)">
    <div style="position:absolute;width: 100%;height:100%;left: 0;top: 0">
        <canvas id="sales-dashboard-bar"></canvas>
    </div>
</div>

and then inside options object of javascript set maintainAspectRatio to false to consider and use parent element height which in this case is absolute positioned and sized relative to the grandparent's size.

var mychart = new Chart(document.getElementById("sales-dashboard-bar"),{
    options: {
        maintainAspectRatio: false,
    }
})

Thus chart will scale nicely with aspect ratio of 2.5 until it hits the maximum height which is 530px here and stops scaling afterwards.

Shashank Bhatt
  • 717
  • 1
  • 11
  • 28
0

I hope this is not late but will help someone.

var canvas = document.getElementById(id);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight / 2.5;  
var ctx = canvas.getContext('2d');

Set the width and the height before you create the chart, adjust the height as you wish.

-2

For react, doing this works:

<Doughnut
  data={data}
  height="200px"
  width="200px"
  options={{ maintainAspectRatio: false }}
/>
Abdulsalam
  • 275
  • 4
  • 6