Reputation: 685
I have data that looks something like this:
groupA = [{'race': 'Black', 'count': 7},
{'race': 'White', 'count': 8},
{'race': 'unknown', 'count': 3}]
groupB = [{'race': 'White', 'count': 5},
{'race': 'Asian', 'count': 8},
{'race': 'Black', 'count': 6},
{'race': 'unknown', 'count': 4}]
groupC = [{'race': 'Black', 'count': 5},
{'race': 'White', 'count': 8},
{'race': 'unknown', 'count': 10},
{'race':'Asian', 'count':5}
{'race': 'Hispanic', 'count': 4}]
//...and so on
I am using it in d3 to build pie charts. I have an html select option to choose which group data to display on the pie chart. Everything works fine except that I want the same color to represent the same category each time a chart is rendered. There are 5 race categories but not every category is represented in each group.
I defined the colors like this:
var race_color = d3.scale.ordinal()
.range(["#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E"]);
I am using this to fill the slices:
arcs.append("svg:path")
.attr("fill", function(d, i){
return race_color(i);
})
.attr("d", function (d) {
return arc(d);
})
But what I need to do is to bind the same race category to the same color slice. How do I go about this?
Upvotes: 0
Views: 475
Reputation: 2897
For example, please prepare color table like this.
var color_table = {
'Black' : '#1B9E77',
'White' : '#D95F02',
'Asian' : '#7570B3',
'Hispanic': '#E7298A',
'unknown' : '#66A61E'
};
And modify your code like this.
arcs.append("svg:path")
.attr("fill", function(d, i){
return color_table[d.race]; // modified
})
.attr("d", function (d) {
return arc(d);
})
Upvotes: 1
Reputation: 25157
Using index position i
, as in race_color(i)
doesn't work because at times, when i
is 0 race is "Black"
(groups A, C), and in another case it's "White"
(group B).
Instead, key the colors by the actual race value race_color(d.race)
, which remains consistent across groups.
Upvotes: 1