简体   繁体   中英

How can I set the height of a chart with ng2-charts

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

I've searched the documentation for ng2-charts and chart.js . In chart.js it looks like you set a height property on the canvas element like <canvas height="400"> , but that element is obscured by the ng2-charts component.

Figured it out.

If responsive: true and maintainAspectRatio: false settings are set, you can then set the css height property of the <base-chart> element.

只需设置 baseChart 的高度属性。

<canvas baseChart height="300" ...></canvas>

just set height and width after basechart

 <canvas   baseChart
       height="40vh" width="80vw"
       [data]="doughnutChart.data"
       [labels]="doughnutChart.label"
       [chartType]="doughnutChartType"
       (chartHover)="chartHovered($event)"
       (chartClick)="chartClicked($event)">
    </canvas>

In the ts file, declare chartOptions as ::

chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
}

Likewise, In html file property bind [options]="chartOptions" and set required height, width in div tag

<div style="display: block; width: 500px; height: 400px;">
  <canvas
      baseChart
      [chartType]="'line'"
      [datasets]="chartData"
      [labels]="chartLabels"
      [colors]="lineChartColors"
      [options]="chartOptions"
      [legend]="true"
      (chartClick)="onChartClick($event)">
  </canvas>
</div>

This will work.

To provide the height or width you need to use a wrapper <div><div/> element around the <canvas><canvas/> element and the div element should then be decorated with relative position style and the height and width with reference to the view port size(browser window size).

This would look like below:

<div class="chart-container" style="position: relative; height:50vh; width:50vw">
      <canvas baseChart
        -----chart property binding here------
      </canvas>
</div>

setting

<canvas style="width: inherit;height: inherit;"

will adapt according to the chart's parent container size

Set the chart options to be responsive

chartOptions: ChartOptions = {
  responsive: true,
  maintainAspectRatio: false,
};

The view width can be set in CSS

.myclass {
   width: 100vw;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM