我正在使用ng2图表。我有一个日期选项卡,可以在其中选择今天,周,月和特定日期。据此,我的数据在图表中有所不同。根据日期,我的数据运行良好。但是我的图表响应不够灵敏,无法绘制与日期对应的值。
今日视图: https://ibb.co/bHDdwLG 数据[100,105,120],
周视图:https://ibb.co/SfWxyMr 数据[100,105,120,140]
如果您看到一周的视图,在完成 value:140 图形之前,它似乎没有响应。
法典
TS
public lineChartOptions: any = {
responsive: true,
};
getabc(start?: moment.Moment, end?: moment.Moment) {
this.abcService.getabc(this.token, start, end).subscribe(
data => {
this.a = data.map(k => k.a);
this.date_time = data.map(k => k.datetime.toLocaleTimeString());
this.lineChartData = [
{ data: this.a, label: 'abc' }
]
this.lineChartLabels=this.date_time
console.log(this.a);
console.log(this.date_time); // I can get the values correctly
according to the date
}
);
}
.HTML
<div style="display: block;" *ngIf="lineChartData.length > 0">
<canvas baseChart width="400" height="180" style="margin-
left:5%;margin-top: 5%;" [datasets]="lineChartData"
[labels]="lineChartLabels" [options]="lineChartOptions"
[colors]="lineChartColors" [legend]="lineChartLegend"
[chartType]="lineChartType" (chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
</div>
这是解决方案(类必须称为 chart
)
<div class="chart">
<canvas baseChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="chartOptions"
legend="true"
chartType="bar">
</canvas>
</div>
.CSS
.chart {
position: relative;
min-height: unset;
}
您需要将维护纵横比设置为 false
public pieChartOptions: ChartOptions = {
responsive: true,
maintainAspectRatio: false,
}
并设置画布高度=>画布底图高度="450"
<canvas baseChart height="450"
[data]="pieChartData"
[labels]="pieChartLabels"
[chartType]="pieChartType"
[options]="pieChartOptions"
[plugins]="pieChartPlugins"
[colors]="pieChartColors"
[legend]="pieChartLegend"
(chartClick)="chartClicked($event)">
</canvas>
您可以使用CSS设置移动高度
@media (max-width: 600px) {
.chartjs-render-monitor {
height: 700px !important;
}
}
不要为画布元素提供宽度和高度,因为它会限制图形完全显示,您应该有一个图表包装器并为其提供宽度,画布将根据可用空间采用大小。
<div class="chart-wrapper">
<canvas baseChart [datasets]="lineChartData" *ngIf="lineChartData.length > 0"
[labels]="lineChartLabels" [options]="lineChartOptions"
[colors]="lineChartColors" [legend]="lineChartLegend"
[chartType]="lineChartType" (chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
在 css 样式中,您的包装器类
.chart-wrapper{
position: relative;
height: 40vh;
max-width:100%;
}