我使用过ChartsJS,但这并不容易。 我想在图表上显示两行项目,但我一次只能显示一行。
我的结果: https://www.dropbox.com/s/wjbee6ze16br00x/Capturar.PNG?dl=0
如何在图表中获得两条或更多线?
我的组件.JS
import { ChartService } from './../service/chart.service';
import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-linea',
templateUrl: './linea.component.html',
styleUrls: ['./linea.component.css']
})
export class LineaComponent implements OnInit {
data_in: Array<any> = [];
labels: Array<any> = [];
options = { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-
digit', minute: '2-digit' };
datasets: Array<any> = [
{ data: [], label: 'Price 24h' },
{ data: [], label: 'Open' }
];
public lineChartType: any = 'line';
public lineChartLegend: any = true;
public lineChartColors: Array<any> = [];
public lineChartOptions: {
responsive: true
};
constructor(private chartService: ChartService) { }
public chartClicked(e: any): void {
console.log(e);
}
public chartHovered(e: any): void {
console.log(e);
}
populateChart(obj) {
const labels: any[] = [];
for (let i = 0; i < obj.length; i++) {
labels.push(new Date(obj[i].time * 1000).toLocaleDateString('de-DE', this.options));
this.datasets[0].data.push(obj[i].close);
this.datasets[1].data.push(obj[i].open);
}
setTimeout(() => { this.data_in = this.datasets;
console.log(this.data_in); } );
this.labels = labels;
}
ngOnInit() {
this.getData();
}
getData() {
this.chartService.getData()
.subscribe(res => { this.populateChart(res); });
}
}
我的组件 HTML:
<div class="row">
<div>
<div>
<canvas baseChart width="400" height="200"
[data]="data_in"
[labels]="labels"
[options]="lineChartOptions"
[colors]="lineChartColors"
[legend]="lineChartLegend"
[chartType]="lineChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
</div>
</div>
我的服务.JS
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class ChartService {
urlBase = 'https://min-api.cryptocompare.com/data/histohour?fsym=BTC&tsym=USD&limit=24';
constructor(private http: Http) { }
getData() {
return this.http.get(this.urlBase)
.map(res => res.json().Data);
}
}
您正在将数据绑定到画布元素/对象的错误属性。当您有多个数据集的数组时,必须将其绑定到datasets
属性,而不是data
。
此外,您应该将类的datasets
属性(不是data_in
(绑定到[datasets]
(这里setTimeout
没有做你认为的那样(
...
<canvas baseChart width="400" height="200"
[datasets]="datasets"
[labels]="labels"
[options]="lineChartOptions"
[colors]="lineChartColors"
[legend]="lineChartLegend"
[chartType]="lineChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)">
</canvas>
...
参见工作示例
(使用所需的最少代码(