我正在尝试使用Dimple.JS和D3创建堆积条形图。但是,我希望与此特定可视化使用的JSON文件涉及嵌套的JSON对象(如下所示)。我想要创建的堆积条形图将通道类别作为其x轴,y轴是不同位置的聚合计数(每个位置为“堆栈”)。这是原始数据:
[{
"channel": "politics",
"locations":
[{
"name":"usa",
"count" : 1454
},
{
"name":"mexico",
"count":3543
},
{
"name":"antarctica",
"count":4352
}]
},
{
"channel": "economics",
"locations":
[{
"name":"usa",
"count" : 12431
},
{
"name":"mexico",
"count":314
},
{
"name":"china",
"count":2321
}]
}]
我已将上面的内容扁平化为下面的JSON,但是我在使用Dimple的.addSeries()方法创建堆栈时遇到了麻烦。
[
{
"channel": "politics",
"locations[0].name": "usa",
"locations[0].count": 1454,
"locations[1].name": "mexico",
"locations[1].count": 3543,
"locations[2].name": "antarctica",
"locations[2].count": 4352
},
{
"channel": "economics",
"locations[0].name": "usa",
"locations[0].count": 12431,
"locations[1].name": "mexico",
"locations[1].count": 314,
"locations[2].name": "china",
"locations[2].count": 2321
}
]
我的问题是:Dimple如何支持这个特定JSON文件中编码的数据?大多数示例使用CSV和TSV文件,但遗憾的是我只能使用JSON文件。
答案 0 :(得分:0)
Dimple不能使用嵌套数据。您必须在客户端将其展平,因此每个通道/位置交叉点都有一个JSON对象。以下是使用Underscore.js进行此操作的示例:
var chartData = _.chain(data)
.map(function(row, index){
// for each original row, return a new row for each location
return _.map(row.locations, function(location){
return {
'channel' : row.channel,
'name' : location.name,
'count' : location.count
};
});
})
.flatten()
.value();
(对于原始数据集中的每一行,它将返回三行,每个位置一行。这将返回一个嵌套数组的数组,因此它调用flatten
使整个数组深入1级。 )
这是一个jsBin,显示在行动中:http://jsbin.com/nuvihu/edit?html,js,output
如果这有帮助,那么数据结果如下:
[{"channel":"politics","name":"usa","count":1454},{"channel":"politics","name":"mexico","count":3543},{"channel":"politics","name":"antarctica","count":4352},{"channel":"economics","name":"usa","count":12431},{"channel":"economics","name":"mexico","count":314},{"channel":"economics","name":"china","count":2321}]