Angular2+ real time data line chart

已查看 51 次
跳至第一个未读帖子

n_ver

未读,
2017年7月21日 05:11:582017/7/21
收件人 d3-js
Hi everybody,
I am struggling trying to achieve a real time line chart in an Angular component.

I used this article as reference https://bost.ocks.org/mike/path/

what is not working for me is the traslation on the x_axes
that translation is performermed only for the first point/data, then no translation is performed

Can please someone help me to figure out how to properly make this?

Here is the code of the component:

import { Component, OnInit, ViewChild, Input, HostListener, ElementRef } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import * as d3 from 'd3';

@Component({
selector: 'app-line-chart',
template: '<div #chart style="width: 100%; height: 100%; margin: 0"></div>',
styleUrls: ['./line-chart.component.scss']
})
export class LineChartComponent implements OnInit {
n;
svg; path; rect; g;
renderedData = [{date: Date.now(), close: 0}];
@ViewChild('chart') chartContainer: ElementRef;
@Input() data: Subject<any>;
@HostListener('window:resize', ['$event'])
onresize(event) {
this.resizeChart()
}

constructor() {
this.n = 100;
const random = d3.randomNormal(0, 100)
const data = d3.range(this.n).map(random)
data.forEach(element => {
this.renderedData.push({date: Date.now(), close: element})
});
}

ngOnInit() {
const el = this.chartContainer.nativeElement;
this.svg = d3.select(el)
.append('svg')

this.rect = this.svg.append('defs').append('clipPath')
.attr('id', 'clip')
.append('rect')

this.path = this.svg.append('g')
.attr('clip-path', 'url(#clip)')
.append('path')


this.resizeChart()

this.data.subscribe(d => this.update(d))
}

resizeChart() {
const el = this.chartContainer.nativeElement;
const w = el.clientWidth;
const h = el.clientHeight;

d3.selectAll('svg')
.style('width', '100%')
.style('height', '100%')
.style('background', '#e5f442')

this.rect.attr('width', w).attr('height', h)
}

update(data) {
const n = 100;
const now = Date.now()
this.renderedData.push({date: now, close: data.payload.x})

const el = this.chartContainer.nativeElement;
const w = el.clientWidth;
const h = el.clientHeight;

const xScale = d3.scaleLinear().domain([0, n - 1]).range([0, w])
const yScale = d3.scaleLinear().domain([-100, 100]).range([h, 0])

const valueline = d3.line()
.x((d, i) => xScale(i))
.y(d => yScale(d.close));

this.path
.data([this.renderedData])
.style('fill', 'none')
.style('stroke-width', 2)
.style('stroke', '#1b3145')
.attr('d', valueline)
.transition()
.duration(500)
.ease(d3.easeLinear)
.attr('transform', null)
.attr('transform', 'translate(' + xScale(-1) + ')')
.transition()

if (this.renderedData.length > n) {
this.renderedData.shift();
}
}
}
回复全部
回复作者
转发
0 个新帖子