过滤数据会导致y轴出错

Filtering my data causes the y-axis to get screwed up

本文关键字:出错 数据 过滤      更新时间:2023-09-26

我正在创建一个列图w/d3。我有263个数据点,显示所有列会使图表过于拥挤。为了过滤数据点,我只需抓取第n项(从数组的反面开始,这样我就可以确保获得最近的数据点)。

我定义y轴刻度值以包含未过滤数据集的最小值和最大值,因此用户可以看到数据集的真实最小值和最大值。我在过滤数据之前计算最小值和最大值:

var v = new Array();
data.forEach(function (d) {
    d.date = parseDate(d.date);
    d.close = +d.close;
    v.push(d.close); // v holds ALL our values...before we filter them
});
yAxisValues = [Math.min.apply(null, v),Math.max.apply(null, v)];
if(data.length > 100){ // make it so that the chart isn't as crowded
        var len = data.length;
        var n = Math.round(len/100); // ideally, we want no more than 100 items
        var tempData = [];
        data = data.reverse();
        for( var k = 0; k < len; k += n ){
            tempData.push( data[ k ] );
        }
        data = tempData;
        data = data.reverse();
    }

然而,现在我的y轴搞砸了,-0.02显示在x轴下方。我做错了什么?我的小提琴。(要查看y轴的正常行为,只需注释掉我过滤数据的部分)

您在过滤之前创建Y轴,但是您仍然在过滤数据上创建刻度:

var y = d3.scale.linear().range([height - 5, 5]);
// here is where it look at the min/max of the filtered data rather than the min/max of the original
y.domain(d3.extent(data, function (d) {
    return d.close;
}));
var yAxis = d3.svg.axis().scale(y).orient('left').tickValues(yAxisValues);

如果你把这部分移动到过滤之前,它应该是OK的