My d3 pie chart reads data from a JSON file, which in this example is represented as an array variable. Some of the key names are not very descriptive, so I am attempting to use a map function to replace certain strings with more meaningful ones. However, there are also key names that I'm fine with and want to keep as they are. If a key name is not defined in my function, it returns undefined and the names are not added to the legend.
While I know all the key names, I prefer to skip over the ones I haven't specifically defined, allowing them to remain unchanged. This way, if new keys are added to the data, the code remains versatile. In a previous test where all key names were declared, while it no longer threw undefined errors, it still didn't add the new key names to the legend.
You can find the full implementation on JSFiddle: https://jsfiddle.net/lharby/ugweordj/6/
Below is a truncated version of my JavaScript function:
var w = 400,
h = 400,
r = 180,
inner = 70,
color = d3.scale.category20c();
data = [{"label":"OOS", "value":194},
{"label":"TH10", "value":567},
{"label":"OK", "value":1314},
{"label":"KO", "value":793},
{"label":"Spark", "value":1929}];
mapData = data.map(function(d){
if(d.label == 'OOS'){
return 'Out of scope';
}else if(d.label == 'TH10'){
return 'Threshold 10';
}else{
// For other keys, no modification needed
continue;
}
});
var total = d3.sum(data, function(d) {
return d3.sum(d3.values(d));
});
var vis = d3.select("#chart")
.append("svg:svg")
.data([data])
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(" + r * 1.1 + "," + r * 1.1 + ")")
var arc = d3.svg.arc()
.innerRadius(inner)
.outerRadius(r);
var pie = d3.layout.pie()
.value(function(d) { return d.value; });
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
var legend = d3.select("#chart").append("svg")
.attr("class", "legend")
.attr("width", r)
.attr("height", r * 2)
.selectAll("g")
.data(mapData)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d, i) { return color(i); });
legend.append("text")
.attr("x", 24)
.attr("y", 9)
.attr("dy", ".35em")
.text(function(d) { return d.label; });
The HTML structure consists of a single element with an ID of #chart
.