简体   繁体   English

d3.js条形图:.text不显示

[英]d3.js bar chart: .text doesn't show up

I'm building a simple bar chart using d3.js and it works fine. 我正在使用d3.js构建一个简单的条形图,并且工作正常。 However, when I try to display texts on each bar, nothing happens. 但是,当我尝试在每个栏中显示文本时,什么也没发生。 The console doesn't return any error so I can't understand the problem. 控制台不会返回任何错误,因此我无法理解问题。 My code is available here , I tried to display simple text like "Hello" but still nothing shows up. 我的代码在此处 ,我试图显示简单的文本,例如“ Hello”,但仍然没有任何显示。

Problem: 问题:

Appending texts to a rect element in SVG. 将文本附加到SVG中的rect元素。

Solution: 解:

Append the texts to the SVG or to a group. 将文本追加到SVG或组中。

Instructions: 说明:

You are appending your texts to the rectangles. 您正在将文本追加到矩形。 Nothing will show up as an error in the console because there is no error to show, but the texts won't appear. 不会在控制台中显示任何错误,因为不会显示任何错误,但是不会显示文本。

You have to create a variable for the texts: 您必须为文本创建一个变量:

var texts = svg.selectAll(".mytexts")
                            .data(data)
                            .enter()
                            .append("text");

And then setting the attributes: 然后设置属性:

texts.attr("class", "value")
              .attr("x", function(d) { return widthScale(d.vacant); })
              .attr("y", heightScale.rangeBand() / 2)
              .attr("dx", -3)
              .attr("dy", ".35em")
              .attr("text-anchor", "end")
              .text(function(d) { return format(d.vacant); });

Don't forget to change the CSS accordingly. 不要忘记相应地更改CSS。

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

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