我的图表尚未工作,但这并不重要,因为我一次只处理一个元素。正如我在上一个问题中所发布的,这是我正在使用的数据:
{
"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; }));
这一行只给了我句点,正是它应该做的事情,因为它只访问图表数据的第一个元素。这是一个包含所有代码的 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/