我想使用d3 v5制作多个折线图。嵌套两次后,我不知道如何正确访问数据。 我的数据如下所示(.json):
[
{
"age": "46-65",
"sex": "Weiblich",
"visit": "3-4 mal im Monat",
"timetable": "3 - befriedigend",
"timelength": "3 - befriedigend"
},
{
"age": "46-65",
"sex": "Weiblich",
"visit": "1-2 mal im Monat",
"timetable": "2 - gut",
"timelength": "3 - befriedigend"
},
{
"age": "31-45",
"sex": "Maennlich",
"visit": "3-4 mal im Monat",
"timetable": "3 - befriedigend",
"timelength": "3 - befriedigend"
},
{
"age": "31-45",
"sex": "Weiblich",
"visit": "Sporadisch",
"timetable": "2 - gut",
"timelength": "2 - gut"
},
{
"age": "46-65",
"sex": "Weiblich",
"visit": "1-2 mal im Monat",
"timetable": "2 - gut",
"timelength": "2 - gut"
},
{
"age": "20-30",
"sex": "Weiblich",
"visit": "1-2 mal im Monat",
"timetable": "3 - befriedigend",
"timelength": "2 - gut"
},
{
"age": "Juenger als 20",
"sex": "Weiblich",
"visit": "3-4 mal im Monat",
"timetable": "2 - gut",
"timelength": "3 - befriedigend"
},
.
.
.
]
使用嵌套数据后
var nest = d3.nest()
.key(d => { return d.age; })
.key(d => { return d.visit; })
.entries(data)
我的数据看起来像这样
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0:
key: "46-65"
values: Array(3)
0: {key: "3-4 mal im Monat", values: Array(26)}
1: {key: "1-2 mal im Monat", values: Array(7)}
2: {key: "Sporadisch", values: Array(4)}
length: 3
__proto__: Array(0)
__proto__: Object
1: {key: "31-45", values: Array(3)}
2: {key: "20-30", values: Array(3)}
3: {key: "aelter als 65", values: Array(2)}
4: {key: "Juenger als 20", values: Array(4)}
5: {key: "", values: Array(2)}
length: 6
__proto__: Array(0)
在我的图表中,我希望每个年龄段有一行显示每个访问组的数量 因此该轴看起来像这样,x轴上的访问组和y轴的数量
在阅读了很多示例之后,我完全迷失了如何正确访问/调用数据的方法 (尤其是https://amber.rbind.io/blog/2017/05/02/d3nest/上的说明)
这就是我到目前为止所得到的:
var nest = d3.nest()
.key(d => { return d.age; })
.key(d => { return d.visit; })
.entries(data)
console.log(nest)
// scales for x and y
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(nest[0].values, d => { return d.values.length; })]);
var xScale = d3.scaleBand()
.range([0, width])
.domain(['3-4 mal im Monat', '1-2 mal im Monat', 'Sporadisch', ''])
.padding(0.2);
//colour scale
var color = d3.scaleOrdinal(d3.schemeCategory10);
// set axis
var xAxis = svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale));
var yAxis = svg.append("g")
.call(d3.axisLeft(yScale));
// Axis labels
svg.append("text")
.attr("class", "axis")
.attr("x", width/2)
.attr("y", height + margin.top)
.style("text-anchor", "middle")
.text("Besuche");
// Add lines to SVG
var line = d3.line().x(d => xScale(d.visit))
.y(d => yScale(d.values.length));
let lines = svg.append('g')
.attr('class', 'lines');
lines.selectAll('.line-group')
.data(nest).enter()
.append('g')
.attr('class', 'line-group')
.append('path')
.attr('class', 'line')
.attr('d', d => line(d.values.age.length))
.style('stroke', (d, i) => color(i));
它确实创建了正确数量的线元素,但是路径为空。如何正确访问数据? 预先感谢!