我正在使用 d3 js 在同一个 svg 元素上显示两个条形图。两个图都有不同的 json 数据源。单独测试时,两个图都显示得很完美。当整个源代码结合起来时,则不然
为了将矩形附加到页面,我使用了以下代码两次(更改了 .attr 的“x”和“y”中的值)
svgd.selectAll("rect")
.data(dataset_dept_errors)
.enter()
.append("rect")
.attr("x", function (d, i) {
return i * 100 + padding_dept; // x position of rect as per i->0,1,2,3,...
})
.attr("y", function (d) {
return (h_dept + yshift_for_dept - yScale(d.NumRuleFailed)); //y position of rect as per (h-value) to prevent inverted range
})
.attr("width", "50") //depending upon domain->no of inputs - with of band is decided acc. to fit in svg
.attr("height", function (d) {
return yScale(d.NumRuleFailed); //depending upon domain->value of inputs - with of band is decided acc. to fit in svg
})
.attr("fill", function (d) { //colour based on values -> more errors - dark coloured bars
return "rgb(" + 100 + "," + 0 + "," + 200 + ")";
})
.attr("stroke", "black");
我读到 selectAll('rect') 将被忽略,或者第二次遇到它时可能无法按预期工作,因此它应该只在一个 svg 上使用一次。 那么我应该如何将下一组矩形附加到我的页面上?
EDIT1:我对于 selectAll('text') 在同一页面上放置多个文本元素也有同样的问题
最佳答案
您可以首先将两个 g
元素附加到 svg
元素,将它们放置在适当的位置,然后在 g
元素内创建图形。
关于javascript - 将两个条形图组合在一个页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37657309/