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

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

entity,code,year,value
Afghanistan,AFG,1990,10.31850413
Afghanistan,1991,10.32701045
Albania,ALB,3.985169898
Albania,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) })
        )

})

谢谢!

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

您只需像这样过滤.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) })
    )
本文链接:https://www.f2er.com/2985574.html

大家都在问