Resize the width and height of the ng2-charts

sridharan picture sridharan · Nov 21, 2016 · Viewed 10.1k times · Source

How do I set a chart's width and height using ng2-charts? I'm making a Bar chart, just like the demo on the ng2-charts site.

public doughnutChartLabels:string[] = ['EMI', 'Car', 'Food', 'Fuel'];
data:number[] = [3350, 5450, 4100, 1000];
  public doughnutChartType:string = 'doughnut';
  options: { responsive: true, }
  colorsEmptyObject: Array<Color> = [{}];
  public datasets: any[] = [
  {
    data: this.data,
    backgroundColor: [
      "#FF6384",
      "#36A2EB",
      "#FFCE56"
    ],
    hoverBackgroundColor: [
      "#FF6384",
      "#36A2EB",
      "#FFCE56"
    ]
  }];
  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }

Answer

HaveSpacesuit picture HaveSpacesuit · May 31, 2017

For rectangular shaped graphs (line, bar) you can include a width and height tag in the html:

<canvas baseChart width="2" height="1"
        [datasets]="chartData"
        [labels]="chartLabels"
        [options]="chartOptions"
        [colors]="chartColors"
        [legend]=true
        chartType=line></canvas>

The width and height set the aspect ratio, not the actual size.

You can do this for square shaped graphs (donut, radar, pie, polar), but it doesn't make as much sense. It will keep a square shape, but with bigger padding on the sides or top and bottom.

Instead, you can set the exact size you want on a div containing the chart:

<div style="display: block; width: 200px; height: 200px;">
    <canvas baseChart
            [data]="doughnutChartData"
            [labels]="doughnutChartLabels"
            [chartType]="doughnutChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>
</div>