【问题标题】:d3 line chart - object diggingd3折线图-对象挖掘
【发布时间】:2018-11-09 14:06:46
【问题描述】:

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

[{
    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))

【问题讨论】:

    标签: javascript arrays object d3.js


    【解决方案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

    【讨论】:

    • 谢谢!完美运行。
    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多