D3.js:访问数组中的对象属性以创建线图 [英] D3.js: Accessing Object Property inside Array for Creating Line Graph
问题描述
我试图使用d3.js创建一个线图与这个数据结构:
I'm trying to create a line graph using d3.js with this data structure:
var dataset1 = [
{"video_name": "Apples", "video_views": 100},
{"video_name": "Oranges", "video_views": 35},
{"video_name": "Grapes", "video_views": 20},
{"video_name": "Avocados", "video_views": 85},
{"video_name": "Tomatoes", "video_views": 60}
]
对象的索引号是x值,video_views是y -值。
The index number of the object is the x-value and the "video_views" is the y-value.
问题:它附加了svg画布,g元素很好,但每个点的x和y值
The problem: It is appending the svg canvas, and the "g" element just fine, but the x and y values for each point in the graph are not being detected, so nothing is showing up.
// Scale values
var Line_xScale = d3.scale.linear()
.domain([0, 100])
.range([0, Line_Graph_Width]);
var Line_yScale = d3.scale.linear()
.domain([0, 100])
.range([0, Line_Graph_Height]);
// This is where I suspect the problem is. //
// SVG path equal to line
var Path_Var = d3.svg.line()
.x(function(d, i) {
return i * 10;
})
.y(function(d) {
return Line_yScale(d.video_views);
});
// Connect Element with Data
group.selectAll('path')
.data(dataset1)
.enter()
.append('path')
.attr('d', Path_Var)
.attr('fill', 'none')
.attr('stroke', '#fff')
.attr('stroke-width', 2);
任何帮助。谢谢阅读。
Any help is appreciated. Thanks for reading.
推荐答案
一种可能的解决方案:
的对象是x-value ... : domain
的x标度改为使用 d3.range的输入索引数组()
:
The index number of the object is the x-value...: domain
of x scale is changed to array of input indexes using d3.range()
:
// Scale values
var Line_xScale = d3.scale.linear()
.domain(d3.range(dataset1.length))
.range([0, Line_Graph_Width]);
...并且video_views是y值。 : range
已更改,因此更大的值位于顶部:
... and the "video_views" is the y-value.: range
is changed so greater values are at the top:
var Line_yScale = d3.scale.linear()
.domain([0, 100])
.range([Line_Graph_Height, 0]);
x线的值更改为计算一点的宽度:
x value of line is changed to calculate width of one point:
var Path_Var = d3.svg.line()
.x(function(d, i) {
return i * Line_Graph_Width / dataset1.length;
})
.y(function(d) {
return Line_yScale(d.video_views);
});
并使用以下线条附加:
group.append('path')
.attr('d', Path_Var(dataset1))
.attr('fill', 'none')
.attr('stroke', '#000')
.attr('stroke-width', 2);
stroke
请参阅 example in jsbin 。
使用 group.selectAll('path')。data(dataset1).enter ('path')
,您将不仅添加一个路径,而且添加dataset1.length路径元素。
Using group.selectAll('path').data(dataset1).enter().append('path')
you would add not just one path but dataset1.length path elements.
这篇关于D3.js:访问数组中的对象属性以创建线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!