如何从数据集中选择一组值以使用 D3 绘制折线图.js而不是整个数据集



我有一个看起来像这样的数据集

entity,code,year,value
Afghanistan,AFG,1990,10.31850413
Afghanistan,AFG,1991,10.32701045
Albania,ALB,1990,3.985169898
Albania,ALB,1991,4.199006705

我想用 D3.js 绘制折线图,但仅适用于代码为"AFG"的国家/地区。 x 轴将是 1990 年至 2017 年的年份,y 轴是值。目前,我的代码采用所有国家/地区,从而创建一个包含一百多条重叠行的折线图。如何更改此代码以使其采用指定的值:

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 60},
width = 560 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg2 = d3.select("#linechart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
//Read the data
d3.csv("./files/suicide-death-rates.csv",

// Now I can use this dataset:
function(data) {
// Add X axis --> it is a date format
var x = d3.scaleLinear()
.domain(d3.extent(data, function(d) { return d.year; }))
.range([ 0, width ]);
svg2.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add Y axis
var y = d3.scaleLinear()
.domain([0, d3.max(data, function(d) { return +d.value; })])
.range([ height, 0 ]);
svg2.append("g")
.call(d3.axisLeft(y));
// Add the line
svg2.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", d3.line()
.x(function(d) { return x(d.year) })
.y(function(d) { return y(d.value) })
)
})

提前感谢!

您只需像这样过滤.datum(data)

// Add the line
svg2.append("path")
.datum(data.filter(f => f.code ==="AFG"))
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", d3.line()
.x(function(d) { return x(d.year) })
.y(function(d) { return y(d.value) })
)

最新更新