简体   繁体   English

Append 不是 d3.js 中的函数吗?

[英]Append is not a function in d3.js?

I am new to D3.js and I have an error I do not understand.我是 D3.js 的新手,我有一个我不明白的错误。 In the style section, I have this在样式部分,我有这个

.bar1 {
  fill: blue;
}

.bar2 {
  fill: red;
}

I my html code I define this ID:我的 html 代码定义了这个 ID:

<div id="chart-svg"></div>

In the JavaScript code, svg is defined like so:在 JavaScript 代码中,svg 的定义如下:

var svg = d3.select("#chart-svg").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("class", "graph")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

then in the javascript I have this definition of some logic to filter code然后在javascript中我定义了一些逻辑来过滤代码

barsM = svg.selectAll(".bar1").data(data).enter()
     .filter(function (d) {
         return (d.location_id == location_id)
             && (d.year == year)
             && (d.metric == metric)
             && (d.sex_id == 1)
     });

And finally最后

barsM.append("rect")
    .attr("class", "bar1")
    .attr("x", function (d) { return x(d.age_group); })
    .attr("width", x.rangeBand() / 2)
    .attr("y", function (d) { return y0(d.mean * 100); })
    .attr("height", function (d, i, j) { return height - y0(d.mean * 100); });

But I have this strange error that says append is not function.但是我有一个奇怪的错误,说 append 不是函数。 Please help请帮忙在此处输入图片说明

This happens when you don't have a selection.当您没有选择时会发生这种情况。 The "append" is not part of the d3 object but the selection. “追加”不是 d3 对象的一部分,而是选择。 I think the problem with your code is that you are filtering after entering your data but the filter should go before the enter method.我认为您的代码的问题在于您在输入数据后进行过滤,但过滤器应该在 enter 方法之前进行。

barsM = svg.selectAll(".bar1").data(data).filter(function (d) {
         return (d.location_id == location_id)
             && (d.year == year)
             && (d.metric == metric)
             && (d.sex_id == 1)
     }).enter();
     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM