我已经使用过ChartsJS,但是这并不容易。
我想在图表上显示两条线,但一次只能显示一条线。

我的结果:
https://www.dropbox.com/s/wjbee6ze16br00x/Capturar.PNG?dl=0

如何在图表中获得两条线或更多?

我的Component.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>


我的服务

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>
...


参见-working example
(使用最少的代码)

09-28 02:41