我正在尝试使用D3js气泡图示例(https://bl.ocks.org/mbostock/4063269),但该示例基于使用CSV文件进行数据。
如何修改示例以使用JavaScript数组而不是CSV文件?
d3.csv("flare.csv", function(d) {
答案 0 :(得分:1)
在链接到的CSV示例中,部分代码在d3.csv
函数的回调函数内执行。换句话说,我们必须等到数据加载才能使用它。
但是,如果您已经拥有数组中的数据,那么您可以立即使用它。我已在程序开头下方显示(注意:未完成):
/* The data doesn't have to be loaded and can be used immediately */
var classes = [
{ id: 'flare', value: 0 },
{ id: 'flare.analytics', value: 0 },
{ id: 'flare.analytics.cluster', value: 0 },
{ id: 'flare.analytics.cluster.AgglomerativeCluster', value: 3938 },
{ id: 'flare.analytics.cluster.CommunityStructure', 3812 },
{ id: 'flare.analytics.cluster.HierarchicalCluster', 6714 },
{ id: 'flare.analytics.cluster.MergeEdge', 743 }
];
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var format = d3.format(",d");
var color = d3.scaleOrdinal(d3.schemeCategory20c);
var pack = d3.pack()
.size([width, height])
.padding(1.5);
/*
This code was inside the d3.csv() callback in the original example,
because we had to wait for the data to be loaded from the csv
to become available.
But as we already have the data in memory in the array,
it can be executed immediately (see the classes array
being used).
*/
var root = d3.hierarchy({ children: classes })
.sum(function(d) { return d.value; })
.each(function(d) {
if (id = d.data.id) {
var id, i = id.lastIndexOf(".");
d.id = id;
d.package = id.slice(0, i);
d.class = id.slice(i + 1);
}
});
//Carry on with rest of script as per the blocks example