Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js aspect ratio / forced height

I'm trying to use chart.js to create thumbnails which will link to pages with the full chart.

The full chart on the linked page looks good but the for the thumbnail I just can't get the sizing right. The canvas is covering the right area but the graph doesn't fill it vertically.

enter image description here

var data = {
    labels: ['','','','','','','','','',''],
    datasets: [{
        data:[22,25,23,24,25,22,25,23,24,25],
            backgroundColor: "rgba(54, 255, 170, 0.4)",
            borderColor: "rgba(54, 255, 170, 1)",
            orderWidth: 1,
    }]
};
var options = {
    tooltips: false,
    legend: {
        display:false
    },
    scales: {
        yAxes: [{
            display:false,
            ticks: {
                beginAtZero:true
            }
        }],
        xAxes: [{
            gridLines: {
                color: "rgba(0, 0, 0, 0)",
            }
        }]
    }
};
            
new Chart($("#chart-"+this.model.id), {
    type: 'bar',
    data: data,
    options: options        
});

I've tried things like adjusting the min-height of the canvas but that causes the bars to blur. Is there any way I can adjust the height of the bars to occupy the whole canvas?

like image 915
Alec Gamble Avatar asked Nov 14 '16 17:11

Alec Gamble


People also ask

What is aspect ratio in Chart JS?

Canvas aspect ratio (i.e. width / height , a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style. The default value varies by chart type; Radial charts (doughnut, pie, polarArea, radar) default to 1 and others default to 2 .

How do I set the size of a Chartjs?

To set the chart size in ChartJS, we recommend using the responsive option, which makes the Chart fill its container. You must wrap the chart canvas tag in a div in order for responsive to take effect. You cannot set the canvas element size directly with responsive .

What is Maintainaspectratio?

If you select the Maintain Aspect Ratio check box, the embedded Mimic will retain its original proportions. This means that when you resize the embedded Mimic, its width and height will maintain their relationship, for example, if you reduce the height, the width will also reduce automatically.


1 Answers

Actually in Chart.js 3.2.1 to update the aspect ratio to add more height to your scheme you can use the aspectRatio option:

options: {          
   aspectRatio: 1, 
}

And so according to the documentation:

Canvas aspect ratio (i.e. width / height, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style.

You can set it such as:

  • 1 for it to be square
  • 0.5 to be twice as high as wide
  • 2 to be twice as wide as high
like image 111
Sylhare Avatar answered Sep 21 '22 12:09

Sylhare