在Angular 9应用中使用Chart.js创建基于日期的多行折线图,可以参考以下步骤:
1.首先要在项目中安装Chart.js和ng2-charts:
npm install chart.js --save
npm install ng2-charts --save
2.导入必要的模块和组件:
在app.module.ts文件中添加以下代码:
import { ChartsModule } from 'ng2-charts'; @NgModule({ imports: [ ChartsModule ], })
3.编写HTML和TypeScript代码:
在component.html文件中添加以下代码:
在component.ts文件中添加以下代码:
import { Component, OnInit } from '@angular/core'; import { ChartDataSets, ChartOptions } from 'chart.js'; import { Color, Label } from 'ng2-charts';
@Component({ selector: 'app-line-chart', templateUrl: './line-chart.component.html', styleUrls: ['./line-chart.component.scss'] }) export class LineChartComponent implements OnInit { chartData: ChartDataSets[]; chartLabels: Label[]; chartOptions: ChartOptions; chartLegend: boolean; chartColors: Color[]; chartType: string; chartDataSets: ChartDataSets[]; chartPlugins = []; chartLegendItems: Array<{ label: string, color: string }>;
ngOnInit(): void { this.chartLabels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; this.chartDataSets = [ { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A', lineTension: 0, }, { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B', lineTension: 0, }, { data: [18, 48, 77, 9, 100, 27, 40], label: 'Series C', lineTension: 0, } ]; this.chartData = this.chartDataSets; this.chartOptions = { responsive: true, scales: { xAxes: [{ ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 10 }, type: 'time', time: { displayFormats: { day: 'MMM D' } } }], yAxes: [{ ticks: { beginAtZero: true } }] } }; this.chartLegend = true; this.chartColors = [ { backgroundColor: 'rgba(56, 128, 255,0.2)', borderColor: 'rgba(56, 128, 255,1)', pointBackgroundColor: 'rgba(56, 128, 255,1)', pointBorderColor: '#fff', pointHoverBackgroundColor: