我有一个JSON数据集:
var data =[
{ "date":"1-May-12","A":68.13,"B":34.12, "C": 33},
{ "date":"30-Apr-12","A":63.98,"B":95.56, "C": 33},
{ "date":"27-Apr-12","A":67.00,"B":57.89, "C": 33},
{ "date":"26-Apr-12","A":89.70,"B":48.54, "C": 33},
{ "date":"25-Apr-12","A":99.00,"B":29.23, "C": 33},
{ "date":"24-Apr-12","A":130.28,"B":99.23, "C": 33},
{ "date":"23-Apr-12","A":166.70,"B":101.34, "C": 33},
{ "date":"20-Apr-12","A":234.98,"B":122.34, "C": 33},
{ "date":"21-Apr-12","A":345.44,"B":134.56, "C": 33},
{ "date":"24-Apr-12","A":130.28,"B":99.23, "C": 33},
{ "date":"25-Apr-12","A":166.70,"B":101.34, "C": 33},
{ "date":"24-Apr-12","A":234.98,"B":122.34, "C": 33},
{ "date":"19-Apr-12","A":345.44,"B":134.56, "C": 33},
{ "date":"18-Apr-12","A":443.34,"B":160.45, "C": 33},
{ "date":"17-Apr-12","A":543.70,"B":180.34, "C": 33},
{ "date":"16-Apr-12","A":580.13,"B":210.23, "C": 33},
{ "date":"13-Apr-12","A":605.23,"B":223.45, "C": 33},
{ "date":"12-Apr-12","A":622.77,"B":201.56, "C": 33},
{ "date":"11-Apr-12","A":626.20,"B":212.67, "C": 33},
{ "date":"10-Apr-12","A":628.44,"B":310.45, "C": 33},
];
目前,如果我想在线图中添加列(例如A和C),我必须执行以下代码
//add column data to domain max field
max =Math.max(d.A, d.C);
y.domain([0, d3.max(data, function(d) { return max})]);
//generate lines
var valuelineA = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.A); });
var valuelineC = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.C); });
//add paths
svg.append("path")
.attr("class", "line")
.attr("d", valuelineA(data));
svg.append("path")
.attr("class", "line")
.style("stroke", "red")
.attr("d", valuelineC(data));
假设我有一个包含列名的数组(如yVals =["A","B"]
)有一种很好的方法可以使用foreach
循环来迭代它们,所以我不需要复制和粘贴代码改变变量?
答案 0 :(得分:0)
Fiddle最终解决方案。创建一个将数据转换为对象{date, value}
的函数。这会创建数据[允许很好地输入多行]。(https://groups.google.com/forum/#!topic/d3-js/8XLzUYLoFnY)
function changeData(data, keyIn){
return data.map(function(d){
var obj = {};
for(const key in d){
if(d.hasOwnProperty(key) && ["date", keyIn].includes(key)){
if(key == "B"){obj.value = d[key]}
else{obj[key] = d[key];}
}
}
return obj;
});
}
然后用
创建你的行var lineFunc = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.value); });
var lines = svg.selectAll("path").data(data)
.enter().append("path")
.attr("d", lineFunc);
如果您在小提琴页面上打开控制台,它将输出最终的数据结构。
我还应该提一下,如果您的数据很大,这将花费一些时间在js中,如果可能的话,您可能想要考虑做数据转换服务器端。