谁能告诉我为什么我的d3条形图没有显示?

时间:2018-11-03 14:57:10

标签: node.js angular d3.js charts

下面的代码应该呈现图形,但由于某种原因,它不是。我不确定为什么,有人吗?我安装了d3,并且在package.json中具有“ @ types / d3”:“ ^ 5.0.1”,以及“ d3”:“ ^ 5.7.0”。

//in component.html
<mat-card>
<h2>Amount Total By Service</h2>
<mat-card-content>
    D3.js graph here
    <svg width='500' height='200'></svg>
</mat-card-content>  
</mat-card>  



//in component.ts
import  * as d3 from 'd3';


constructor(private http: HttpClient, private router: Router) {
 //this.http.get('/api/home', {}).subscribe(res => { 
 this.invoices = res;   console.log(res), (err) => {console.log(err)}})
 this.invoices = this.http.get('/api/home/' + localStorage.getItem('username'),  {});
 this.buildChart();
 }

buildChart(){
var data = [80, 120, 60, 150,200];
var svgWidth = 500, svgHeight = 200, barPadding = 5;
var barWidth = (svgWidth / data.length);

var svg = d3.select('svg')
      .attr('width', svgWidth)
      .attr('height', svgHeight);
svg.selectAll("rect")
      .data(data)
      .enter()
      .append('rect')
      .attr("y", function(d){
        return svgHeight - d
      })
      .attr("height", function(d) {
        return d
      })
      .attr("width", barWidth - barPadding)
      .attr("fill", "red")
      .attr("transform", function(d, i){
        var translate = [barWidth * i, 0];
        return "translate(" + translate + ")";
      })
}

我刚刚发现该标志与它无关。需要按两次该按钮以呈现图表。错误是在“开始构建图表”          //console.log first click start of buildchart home.component.ts:71 Selection { _groups: Array(1), _parents: Array(1) } _groups: Array(1) 0: [null] length: 1 __proto__: Array(0) _parents: [html] __proto__: Object //console.log second click home.component.ts:47 start of buildchart home.component.ts:71 Selection { _groups: Array(1), _parents: Array(1) } _groups: Array(1) 0: [svg] length: 1 __proto__: Array(0) _parents: [html] __proto__: Object

1 个答案:

答案 0 :(得分:0)

仅测试d3代码似乎有效。请参见下面的代码段。 似乎您在Angular组件中使用代码,请注意组件的生命周期。在codepen https://codepen.io/anon/pen/epLNVZ

上查看此示例

function buildChart() {
var data = [80, 120, 60, 150,200];
var svgWidth = 500, svgHeight = 200, barPadding = 5;
var barWidth = (svgWidth / data.length);

var svg = d3.select('svg')
      .attr('width', svgWidth)
      .attr('height', svgHeight);
svg.selectAll("rect")
      .data(data)
      .enter()
      .append('rect')
      .attr("y", function(d){
        return svgHeight - d
      })
      .attr("height", function(d) {
        return d
      })
      .attr("width", barWidth - barPadding)
      .attr("fill", "red")
      .attr("transform", function(d, i){
        var translate = [barWidth * i, 0];
        return "translate(" + translate + ")";
      })
}
buildChart();
<svg width='500' height='200'></svg>

<script src="https://d3js.org/d3.v5.min.js"></script>