This fiddle pretty much explains what I'm trying to accomplish.
It shows the problem and a proposed solution, but I wonder if my solution is 'right'.
Basically I have JSON that represents a week of scores among teams.
games = [
{
hometeam : "scouts",
homeTeamScore : "21",
visitor : "sharks",
visitorScore : "17"
},
{
hometeam : "gators",
homeTeamScore : "28",
visitor : "wild cats",
visitorScore : "24"
}
]
How would one make a bar chart where each game outputs two bars representing each teams score (two bars from one element of the array)? It would look like this:
-----------------scouts 21
-----------sharks 17
-------------------gators 28
----------------wild cats 24
I cant seem to get my mind around how I can output each teams score using the single element in the array doing .data(games).enter().append() since I 'think' I can only output one entry for each array element.
I can do it if I generate my own array, not a problem (see the fiddle), but is that the best, most d3ish way to handle a situation like this?
Again: here is the fiddle link
A common "trick" is to save the .enter()
selection and operate on it multiple times. This achieves exactly what you want:
var divs = d3.select('.chart2')
.selectAll('div')
.data(data)
.enter();
divs.insert('div')
.attr("class", 'home')
.style("width", function(d) {
return d.hs * 10 + "px";
})
.text(function(d) {
return d.hnn + ' ' + d.hs;
});
divs.insert('div')
.attr("class", 'visitor')
.style("width", function(d) {
return d.vs * 10 + "px";
})
.text(function(d) {
return d.vnn + ' ' + d.vs;
});
Complete example here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.