我是D3js的新手,并希望以动态的方式使用它,也就是说,基于用户想要绘制的数据系列,我希望能够将变量传递给用于解析的函数从csv文件中提取时的数据。
我发现的示例中的代码段都显示从csv或tsv文件读取数据:
d3.tsv("data.tsv", function(error, data) {
if (error) throw error;
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
指定csv标头/密钥。我想将d.date和d.close替换为将传递给函数的变量(即varX和varY),以便显示的数据可以变化。我想到的功能结构是:
function BarChart(filePath,varX,varY,loc){
//put in the code above modified to use varX and varY in place of d.date and d.close
//other code required to create the chart
}
我尝试了几种不同的方式(使用d.varX,或者只是varX)并在网上做了很多阅读以找到一些但却无法完成这项工作的方法。我不确定D3js是否意味着以这种方式使用。任何帮助将不胜感激。
感谢。
答案 0 :(得分:0)
你可以这样打电话:
graph({height: 200, width:400, id: "ccag", xE:d3.scale.ordinal().domain(["I", " II", "III", "IV", "V"]),
data: [[{ x: 0, y: 109117 },{ x: 1, y: 22546 },{ x: 2, y: 29449 },{ x: 3, y: 43711 },{ x: 4, y: 26604 }],[{ x: 0, y: 7481 },{ x: 1, y: 5328 },{ x: 2, y: 10315 },{ x: 3, y: 6218 },{ x: 4, y: 4330 }]],
color:[["#1c3848"],["#36a8e1"]]
})();
然后你的函数绘制图形:
function graph(a) {
return function () {
var margin = {top: 20, right: 20, bottom: 20, left: 35},
w = a.width - margin.left - margin.right,
h = a.height - margin.top - margin.bottom,
fnum = d3.format(",");
//Original data
var ccad = a.data;
var stack = d3.layout.stack();
//Data, stacked
stack(ccad);
.....
.....
或者您可以将文件名传递给函数:
graph({file:"newTSV.tsv"})
然后你的功能:
function graph(a) {
return function () {
d3.tsv(a.file, function(data) { ....