我的图表尚未运行,但这并不重要,因为我一次只处理一个元素。正如我在上一个问题中发布的那样,这是我正在使用的数据:
{
"chartData":[
{
"vId":307,
"vNm":"Alejandro Rivera Ulloa",
"values":[
{"period":"2015-01","amount":37,"id":132},
{"period":"2015-02","amount":38,"id":133},
{"period":"2015-03","amount":33,"id":134}
]
},
{
"vId":308,
"vNm": "Daniel Torres",
"values": [
{"period":"2015-01","amount":41,"id":135},
{"period":"2015-02","amount":41,"id":136},
{"period":"2015-03","amount":41,"id":137}
]
},
{
"vId":309,
"vNm": "Pablo Alvarez Garcia",
"values":[
{"period":"2015-01","amount":16,"id":138},
{"period":"2015-02","amount":17,"id":139},
{"period":"2015-03","amount":14,"id":140}
]
},
{
"vId":391,
"vNm":"Janette Avalos de Conte",
"values":[
{"period":"2015-01","amount":28.5,"id":141},
{"period":"2015-02","amount":29,"id":142},
{"period":"2015-03","amount":27.5,"id":143}
]
}
]
}
一切都很好,我的代码也很好地加载了数据。这是foreach,它使我可以无所不在(简单地说):
data.chartData.forEach(function(kv){
var vNmName = kv.vNm;
var vIdName = kv.vId;
kv.values.forEach(function(d){
d.period = d.period;
d.id = d.id;
d.amount = +d.amount;
d.vNm = vNmName;
d.vId = vIdName;
});
});
所以这就是我所需要的。我的X域显示不正确,我知道为什么。这是代码行:
x.domain(data.chartData[0].values.map(function(d) { return d.period; }));
这行代码仅显示chartData的第一个元素,因此只提供了句点,正是它应该执行的操作。这是带有所有代码的JSFiddle:Fiddle
最佳答案
要回答您的直接问题,如何:
var xDomain = []
data.forEach(function(d){
d.values.forEach(function(v){
if (xDomain.indexOf(v.period) === -1){
xDomain.push(v.period);
}
});
});
xDomain.sort();
x.domain(xDomain);
刻度显示为
NAN
,因为您使用了错误的格式:var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.outerTickSize(0);
//.tickFormat(d3.format("d")); //<-- this says convert to integer, your string dates don't convert to integer
更新了fiddle。
关于javascript - 如何将X域设置为嵌套值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31751277/