是否可以在sankey图中显示总数?
例如,小提琴波纹管显示Fruits>地点。我想知道有多少水果是喜欢的地方和地方有多少水果相关联。如下所示:
Mango (3)
Apple (2)
Pineapple (1)
所有三个都与地点A相关联,因此地点A应为:
(7) Place A
(另外1个是因为葡萄)
http://jsfiddle.net/Khrys/5c2urqbx/
更新:默认情况下看起来v42增加了重量。
答案 0 :(得分:4)
看看这个jsfiddle
码
data1 = [
['Apple', 'Place A', 1],
['Apple', 'Place A', 1],
['Grape', 'Place A', 1],
['Grape', 'Place B', 2],
['Pineapple', 'Place A', 1],
['Strawberry', 'Place B', 4],
['Mango', 'Place A', 3]
];
var sourceTotals = {};
for (var i = 0; i < data1.length; i++) {
var item = data1[i],
key = item[0];
if (sourceTotals.hasOwnProperty(key)) {
sourceTotals[key] += item[2];
}
else {
sourceTotals[key] = item[2];
}
}
console.log(sourceTotals);
var destTotals = {};
for (var i = 0; i < data1.length; i++) {
var item = data1[i],
key = item[1];
if (destTotals.hasOwnProperty(key)) {
destTotals[key] += item[2];
}
else {
destTotals[key] = item[2];
}
}
console.log(destTotals);
data1.forEach( function(d) {
d[0] = d[0] + " (" + sourceTotals[d[0]] + ")";
d[1] = "(" + destTotals[d[1]] + ") " + d[1];
})
答案 1 :(得分:2)
这解决了当您具有多级sankey图时可接受的答案的问题
有关计算“ sourceTotals”和“ destTotals”的信息,请参阅原始答案。
假设我有一些带有多层Sankey图数据的arr“图表”
this.chart = {
type: 'Sankey',
title: '',
data: [
[ 'USA', 'Mexico', 15 ],
[ 'USA', 'Brazil', 16 ],
[ 'South America', 'Mexico', 4 ],
[ 'South America', 'Brazil', 4 ],
[ 'Jamaica', 'Mexico', 18 ],
[ 'South Africa', 'Brazil', 2 ],
[ 'England', 'Brazil', 9 ],
[ 'England', 'Mexico', 9 ],
[ 'Mexico', 'Japan', 4 ],
[ 'Mexico', 'North Pole', 4 ],
[ 'China', 'Denmark', 5 ],
[ 'China', 'Canada', 7 ],
[ 'Mexico', 'China', 10 ],
],
}
首先出现在sourceTotals对象中的删除目标键
for (const key in destTotals) {
if (destTotals.hasOwnProperty(key)) {
if (sourceTotals.hasOwnProperty(key)) {
delete sourceTotals[key];
}
}
}
isKeyInObject(query, object) {
for (const key in object) {
if (object.hasOwnProperty(query)) {
return true;
}
}
return false;
}
this.chart.data.forEach( (d) => {
// Check if d[0] key is in source totals
if (this.isKeyInObject(d[0], sourceTotals)) {
d[0] = d[0] + ' (' + sourceTotals[d[0]] + ')';
}
// check of d[1] key exists in dest totals
if (this.isKeyInObject(d[1], destTotals)) {
d[1] = '(' + destTotals[d[1]] + ') ' + d[1];
}
// deal with destination keys in source index in original arr
// check if key in position 0 of original chart data is available in destTotals object
// change its name to the name key in destTotals
if (this.isKeyInObject(d[0], destTotals)) {
console.log('POS_ZERO_IN_DEST', d[0]);
d[0] = '(' + destTotals[d[0]] + ') ' + d[0];
}
});
答案 2 :(得分:0)
如果您使用d3.js sankey,它将自动对值进行求和,并按照此示例在工具提示中显示... http://bl.ocks.org/d3noob/c9b90689c1438f57d649