[英]Adding labels to a d3 horizontal bar chart?
I'm quite new to d3, I have a very simple bar chart that is 50px wide for every number that I pass it per row. 我对d3相当陌生,我有一个非常简单的条形图,对于每行传递的每个数字,其宽度均为50px。 I'm trying to add labels to go before the bar itself so that a viewer can make sense of what it represents. 我正在尝试添加标签,使其位于酒吧本身之前,以便查看者可以理解其代表的含义。
Here's my code: 这是我的代码:
var data2 = [4, 3, 1, 1];
var fwSkills = ["a", "b", "c", "d"];
d3.select(".frameworks")
.selectAll("div")
.data(data2)
.enter().append("div")
.style("width", function(e) { return e * 50 + "px"; })
.text(function(e) { return e; });
This doesn't add the labels at all, but everything I've tried so far doesn't work (or at least doesn't render the bar correctly). 这根本不会添加标签,但是到目前为止我尝试过的所有方法都不起作用(或者至少不能正确显示该栏)。 There's a bit of CSS to style the bar itself as well. 还有一些CSS可以对栏本身进行样式设置。 I want to add the labels in the array fwSkills to be in front of their respective bars. 我想将标签添加到数组fwSkills中 ,使其位于相应栏的前面。
What can I do here? 我在这里可以做什么? I feel that it's a simple JS fix. 我觉得这是一个简单的JS修复程序。 Thank you! 谢谢!
You could append a div element for each data value. 您可以为每个数据值附加一个div元素。 Then inside each of those div elements, you could append a div element for the label and a div element for the bar. 然后,在每个div元素内,您可以为标签添加div元素,为酒吧添加div元素。 For example... 例如...
var data2 = [4, 3, 1, 1]; var fwSkills = ["a", "b", "c", "d"]; var divs = d3.select(".frameworks") .selectAll("div") .data(data2) .enter() .append("div"); // add labels divs.append("div") .classed("label", true) .style("width", "20px") .text(function (e,i ) { return fwSkills[i]; }); // add bars divs.append("div") .classed("bar", true) .style("width", function(e) { return e * 50 + "px"; }) .text(function(e) { return e; });
.label { display: inline-block; } .bar { display: inline-block; background-color: steelBlue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <div class="frameworks"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.