Reputation: 8892
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. 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. I want to add the labels in the array fwSkills to be in front of their respective bars.
What can I do here? I feel that it's a simple JS fix. Thank you!
Upvotes: 0
Views: 926
Reputation: 3335
You could append a div element for each data value. Then inside each of those div elements, you could append a div element for the label and a div element for the bar. 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>
Upvotes: 1