d3 JSON多折线图 [英] d3 JSON multiple line chart
问题描述
{ 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中的数据。我尝试了各种方式,如
var line = d3.svg.line()
.interpolate )
.x(function(d){return x(d.mon);})
.y(function(d){return y(d.val);});
svg.selectAll(。line)
.data(series)
.enter()。append(path)
.attr ,line)
.attr(d,line);
但我似乎无法将数据导入SVG行。有什么建议么?有没有更好的方式来构建JSON?
这里是什么工作,以防其他人遇到这个问题。诀窍是传递一个函数,该函数返回路径元素的d属性中的关联数组中的值。
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 ,line)
//函数(d),不仅仅是行函数
.attr(d,function(d){return line(d.value);})
.attr(stroke,function(d){return colors(d.key)});
这个答案的一些帮助:
使用JavaScript D3问题嵌套数据
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}, ...]
}
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);
But I can't seem to get the data into the SVG line. Any suggestions? Is there a better way to structure the JSON?
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) });
Some help from this answer too: Using nested data with javascript D3 problem
这篇关于d3 JSON多折线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!