【发布时间】:2015-12-15 14:33:24
【问题描述】:
我正在尝试从 nvd3 修改 Line Plus Bar chart,以便在单击按钮时,图表将切换到一周中不同日期(周日至周六)的数据。
现在我无法让它显示一周中某一天的数据;由于某种原因,它显示一周中的所有日子。这是我的代码:
d3.json("employee_data.json",function(error,data) {
if(error) return console.warn(error);
nv.addGraph(function() {
var chart = nv.models.linePlusBarChart()
.margin({top: 30, right: 60, bottom: 50, left: 70})
//We can set x data accessor to use index. Reason? So the bars all appear evenly spaced.
.x(function(d,i) {
console.log(i)
return i })
.y(function(d,i) {
return d[1] })
;
chart.xAxis.tickFormat(function(d,i) {
var dx = data[0].values[i] && data[0].values[i][0] || 0;
return 'Sun' + dx
});
chart.y1Axis
.tickFormat(d3.format(',f'));
chart.y2Axis
.tickFormat(function(d) { return d3.format(',f')(d) });
chart.bars.forceY([0]);
d3.select('#chart svg')
.datum(data)
.transition()
.duration(0)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
});
JSON 的设置方式类似于:
[
{
"key" : "Sun_Employees",
"bar" : true,
"color" : "#ccf",
"values" : [[0,2],[1,2],[3,2],[4,3],...,[23,1]]
},
{
"key": "Sun_Tasks",
"color" : "#333",
"values" : [[0,5],[1,6],[2,5],[3,7],...,[23,2]]
},
{
"key" : "Mon_Employees",
"bar" : true,
"color" : "#ccf",
"values" : [[0,2],[1,2],[3,2],[4,3],...,[23,1]]
},
{
"key": "Mon_Tasks",
"color" : "#333",
"values" : [[0,5],[1,6],[2,5],[3,7],...,[23,2]]
}
}
我认为问题与 .x(function(d,i) { return i}) 行有关,但不知道如何限制它。
【问题讨论】:
-
您可以在将数据绑定到您的选择之前过滤数据吗?这看起来像:
var filteredData = data.filter(function(d) { return d.key.startsWith("Sun"); }); d3.select('#chart svg').datum(filteredData)... -
是的!这行得通。非常感谢:)
-
太好了,我很高兴听到这个消息!我将我的评论转换为答案,以便您接受。
标签: javascript json d3.js nvd3.js