d3路径d = MNaN,NaNLNaN,NaN

时间:2018-11-08 14:15:58

标签: javascript arrays object d3.js

试图建立一个折线图(多行)。初始数据是一个对象数组,例如:

[{
    2010: 8236.082,
    countryName: "Afghanistan"
}]

每行都需要一个x / y对[[x,y],[x,y]]的数组。我的xyyearamount的排放量。这意味着我必须重组数据使其看起来像这样:

[
     {
         country: "Afganistan",
         emissions: [
             { year: 2019, amount: 8236.082 }
         ]
     }
]

数据整理之后,我陷入了路径d = MNaN,NaNLNaN,NaN的问题。我在这里做什么错了?

Codepen

//Define full width, full height and margins
let fullWidth = 600;
let fullHeight = 700;
let margin = {
    top: 20,
    left: 70,
    bottom: 100,
    right: 10
}

//Define line chart with and height 
let width = fullWidth - margin.left - margin.right;
let height = fullHeight - margin.top - margin.bottom;

//Define x and y scale range
let xScale = d3.scaleLinear()
    .range([0, width])

let yScale = d3.scaleLinear()
    .range([0, height])

//Draw svg
let svg = d3.select("body")
    .attr("width", fullWidth)
    .attr("height", fullHeight)
    .append("svg")
    .append("g")

d3.json("https://api.myjson.com/bins/izmg6").then(data => {
    console.log(data);



    //Structure data so should be an array of arrays  etc [[x,y], [x,y], [x,y]]

    let years = d3.keys(data[0]).slice(0, 50);
    console.log(years);

    let dataset = [];

    data.forEach((d, i) => {

        let myEmissions = [];

        years.forEach(y => {
            if (d[y]) {

                myEmissions.push({
                    year: y,
                    amount: d[y]
                })
            }
        })

        dataset.push({
            country: d.countryName,
            emissions: myEmissions
        });
    })

    console.log(dataset);

    //Define x and y domain
    xScale
        .domain(d3.extent(years))

    yScale
        .domain([d3.max(dataset, d =>
        d3.max(d.emissions, d =>
            +d.amount)), 0])


        //Generate line
    let line = d3.line()
                .x(d => {
                    xScale(d.year);
                })
                .y(d => {
                    yScale(d.amount);
                });


    let groups = d3.selectAll("g")
        .data(dataset)
        .enter()
        .append("g")

    groups.append("title")
        .text(d => d.country)

    groups.selectAll("path")
        .data(d => [d.emissions])
        .enter()
        .append("path")
        .attr("d", line)
        .attr("class", line)

}).catch(error => console.log(error))

1 个答案:

答案 0 :(得分:-1)

NaN的主要问题是

let line = d3.line()
   .x(d => xScale(d.year) )
   .y(d => yScale(d.amount) );

但这不是图表的唯一问题。