[英]Specifying the country column in D3.js pie chart to only list down certain columns
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(['#'+(Math.random()*0xFFFFFF<<0).toString(16),'#'+(Math.random()*0xFFFFFF<<0).toString(16)]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.deaths; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.csv("Cancer_No_Of_Deaths_per_100000.csv", function(error, data) {
data.forEach(function(d) {
d.deaths = +d.deaths;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.country + " " + d.data.gender); })
.on("mouseover", function() {
pie.transition()
.duration(200)
.style("opacity", .9);
})
.on("mouseout", function(d) {
pie.transition()
.duration(500)
.style("opacity", 0);
});
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.style("font-size", "20px")
.text(function(d) { return d.data.country + " " + d.data.gender; });
});
</script>
我希望能够在csv中指定“国家/地区”列,以便仅在饼图示例中仅列出一个国家/地区,其中“国家=”“阿富汗”,而该国家/地区的其余部分将被忽略,但在我的csv文件中不会删除有。 我现在拥有的代码显示的是csv文件中列出的所有国家/地区,但我只希望从csv文件中检索一个国家/地区。
country year gender deaths
Afghanistan 2008 Female 97
Afghanistan 2008 Male 108
Albania 2008 Female 126
Albania 2008 Male 172
这是我的csv文件的一小部分,各列如下。
您可以在d3.csv
回调中的数据数组上使用Array.prototype.filter
。 在过滤器回调中,您可以简单地测试国家/地区名称是否是您想要的名称。 例如,要获取仅包含阿富汗行的数组,可以执行以下操作:
d3.csv('Cancer_No_Of_Deaths_per_100000.csv', function(error, data) {
var filteredData = data.filter(function(d) {
return d.country === 'Afghanistan';
});
// ... create your viz, etc. ...
});
然后,您将可以访问原始数据集作为变量data
,而只有阿富汗数据的集合可以作为filteredData
或任何您选择调用的集合。
- -编辑 - -
现在,您的变量data
将如下所示:
[
{ country: 'Afghanistan', year: '2008', gender: 'Female', deaths: '97' },
{ country: 'Afghanistan', year: '2008', gender: 'Male', deaths: '108' },
{ country: 'Albania', year: '2008', gender: 'Female', deaths: '126' },
{ country: 'Albania', year: '2008', gender: 'Male', deaths: '172' },
// etc... many other countries...
]
您的变量filteredData
将如下所示:
[
{ country: 'Afghanistan', year: '2008', gender: 'Female', deaths: '97' },
{ country: 'Afghanistan', year: '2008', gender: 'Male', deaths: '108' }
]
因此,您只需要确保在pie()
调用中使用过滤后的数据即可:
var g = svg.selectAll(".arc")
.data(pie(filteredData))
.enter().append("g")
.attr("class", "arc");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.