1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

SUPER DUPER PERFECT! Thank you mucho Lars. That's the one combination I didn't think about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.