d3折线图-对象挖掘

时间:2018-11-09 14:06:47

标签: javascript arrays object d3.js

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

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

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

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

但是,这对我不起作用。问题出在域上吗? 请帮忙。

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, d =>d))

    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 = svg.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)

微小变化/典型:

您正在将heightwidth分配给body,而不是svg。交换这两行:

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

并将一些CSS添加到路径

path.line {
  fill: none;
  stroke: #000; 
}

这是叉子:https://codepen.io/shashank2104/pen/GwqjVK