user2628641
user2628641

Reputation: 2154

d3: key function choice when appending element to an existing svg

I read the blog post here: http://knowledgestockpile.blogspot.com/2012/01/understanding-selectall-data-enter.html

and have a question about it.

I have 2 datasets

var dataset1 = [5, 10, 15, 20, 25];
var dataset2 = [11, 12, 13, 14, 15];

I want to create a blue bar chart for dataset1 and append a green bar chart for dataset2, in the same svg.

When I append I did:

svg.selectAll("rect")
        .data(dataset2, function(d) { return d; })
        .enter()

Like the blog post suggested, I use a specific key function here (returning the actual value in the dataset). But since 15 appears in both sets, I miss 15 for the green bar chart.

What is the best way (key function I should use) to avoid that?

my whole code is in this JSfiddle: http://jsfiddle.net/ypeng42/pwm5mmcz/25/

Upvotes: 0

Views: 70

Answers (1)

Mauricio Poppe
Mauricio Poppe

Reputation: 4876

Reason

You're joining your datasets, first consider the initial call to svg.selectAll('rect').data(dataset1)

svg.selectAll('rect').data(dataset1)
- enter: [5, 10, 15, 20, 25]
- update: []
- exit: []

Then the second dataset is joined with the first

svg.selectAll('rect').data(dataset2)
- enter: [11, 12, 13, 14]
- update: [15]
- exit: [5, 10, 20, 25]

You don't have code for update nor exit and that's why the 15 is still blue

Solution

Make your attribute interactions work differently for each dataset by adding a restriction e.g. a class

svg.selectAll("rect.blue")
    .data(dataset1)
    .enter()
    .append('rect')
    .attr('class', 'blue')

svg.selectAll("rect.green")
    .data(dataset2)
    .enter()
    .append('rect')
    .attr('class', 'green')

Personally I'd create the following structure

 <svg>
   <g class="first">
      nodes for the first dataset
   <g class="second">
      nodes for the second dataset

demo

Upvotes: 1

Related Questions