[英]D3 Scatter Plot With Nested Array
I am trying to create a scatter plot using D3 but only two of the points show up. 我正在尝试使用D3创建散点图,但仅显示两个点。
My data has this format 我的数据具有这种格式
var data = [
{
key: "group1",
x: [10,20],
y: [10,30],
label: ["point1", "point2"]
},
{
{
key: "group2",
x: [5,10,25],
y: [20,25,15],
label: ["point3", "point4", "point5"]
},
},
];
The x and y go together, for example in "goup1" the points are (10,10) and (20,30) and in "goup2" the points are (5,20), (10,25), and (25,15). x和y在一起,例如,在“ goup1”中,点是(10,10)和(20,30),在“ goup2”中,点是(5,20),(10,25)和(25 ,15)。 I want to draw all five points on the scatter plot. 我想在散点图上绘制所有五个点。
And I am drawing the points with this 我在此画点
var scatterPlotCircles = this.scatterChartContainer.selectAll(".scatterPlotDots")
.data(data)
.enter().append("circle")
.attr("class", "scatterPlotDots")
.attr("cx",function(d,i){
return scatterChartXScale(d.x[i]);
})
.attr("cy",function(d,i)
{
return scatterChartYScale(d.y[i]);
})
.attr("r", 5)
.attr("fill", function(d,i){ return color(d.key); })
.style("opacity", 1);
I don't think that I am accessing the data correctly. 我认为我无法正确访问数据。 Does anyone know how to correctly access the data to plot them on the graph? 有谁知道如何正确访问数据以在图表上绘制它们?
I find the easiest option is to restructure the data to match the intended SVG. 我发现最简单的选择是重组数据以匹配预期的SVG。
// restructure the data to make life easier
data = data.map(function(d) {
return {
key: d.key,
points: d.label.map(function (l, i) {
return {
label: l,
x: d.x[i],
y: d.y[i]
};
})
};
});
Then it's just a matter of creating a <g>
container for each group. 然后,只需为每个组创建一个<g>
容器即可。
var scatterPlotGroups = scatterChartContainer.selectAll(".scatterPlotGroup")
.data(data)
.enter().append("g")
.attr("class", "scatterPlotGroup");
var scatterPlotCircles = scatterPlotGroups.selectAll("circle")
.data(function(d) { return d.points; })
.enter().append("circle")
.attr("cx", function(d) { return scatterChartXScale(d.x); })
.attr("cy", function(d) { return scatterChartYScale(d.y); })
.attr("r", 5)
.attr("fill", function() { return color(d3.select(this.parentNode).datum().key); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.