d3 JSON 多折线图 [英] d3 JSON multiple line chart

查看:27
本文介绍了d3 JSON 多折线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 JSON blob 中绘制多行的图,如下所示:

I'm trying to make a plot with multiple lines on it from a JSON blob that looks like:

{"2007": [{"val":10, "mon":10}, {"val":20, "mon":11}, {"val":40, "mon":12}, ...],
 "2008": [{"val":20, "mon":8}, {"val":20, "mon":9}, {"val":40, "mon":10}, ...],
  ...
 "2012": [{"val":40, "mon":8}, {"val":50, "mon":9}, {"val":60, "mon":10}, ...]
}

数据基本上是每年的月度总数,有些年份有些月份没有数据.不过,我无法确切地弄清楚如何解析 d3 中的数据.我尝试了各种方法,例如

The data is basically monthly totals for each year, with some years not having data for some months. I can't figure out exactly how to parse the data in d3 though. I tried various ways such as

var line = d3.svg.line()
 .interpolate("basis")
.x(function(d) { return x(d.mon); })
.y(function(d) { return y(d.val); });

svg.selectAll(".line")
 .data(series)
 .enter().append("path")
 .attr("class", "line")
 .attr("d", line);

但我似乎无法将数据放入 SVG 行中.有什么建议?有没有更好的方法来构建 JSON?

But I can't seem to get the data into the SVG line. Any suggestions? Is there a better way to structure the JSON?

推荐答案

以下是解决方案,以防其他人遇到此问题.诀窍是传递一个函数,该函数返回路径元素的d"属性中关联数组中的值.

Here's what worked out in case anyone else runs across this problem. The trick is to pass a function that returns the values in the associative array in the "d" attribute of the path element.

  entries = d3.entries(data);

  var colors = d3.scale.category20()
    .domain(d3.keys(data));

  var line = d3.svg.line()
    .interpolate("basis")
    .x(function(d) { return x(d.month) })
    .y(function(d) { return y(d.value) });

  svg1.selectAll(".line")
    .data(entries)
  .enter().append("path")
    .attr("class", "line")
    // function(d), not just line function 
    .attr("d", function(d){ return  line(d.value); })
    .attr("stroke", function(d) { return colors(d.key) });

这个答案也有一些帮助:使用嵌套数据处理 javascript D3 问题

Some help from this answer too: Using nested data with javascript D3 problem

这篇关于d3 JSON 多折线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆