跨多个图表获取十字准线值

Get crosshair values across multiple Flot Charts

我在我的一个项目中使用 jQuery Flot Charts 插件。我有几个图表站在同一列中,我想做的是:如果您将鼠标悬停在其中任何一个图表上,则在所有图表上显示十字准线。我正在使用以下代码成功完成此操作。

//graphs - this is an object which contains the references to all of my graphs.

$.each(graphs, function(key, value) {
    $(key).bind("plothover",  function (event, pos, item) {
        $.each(graphs, function(innerKey, innerValue) {
            if(key != innerKey) {
                innerValue.setCrosshair({x: pos.x});
            }
        });
        if(item) {
            var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(2);
            console.log("x:" + x + ", " + "y:" + y);
        }
    });
});

我正在遍历图表,添加十字准线并将其相互绑定。所以,现在,当您将鼠标悬停在其中一张图表上时,您会看到十字线在所有其他图表上的相同位置。

没问题。但是我的代码的第二部分有问题:

if(item) {
    var x = item.datapoint[0].toFixed(2),
        y = item.datapoint[1].toFixed(2);
    console.log("x:" + x + ", " + "y:" + y);
}

问题是,只有当我用鼠标悬停实际点时,我才让 console.log 打印值,而我想在十字准线穿过该点时获取该值,不一定是鼠标指针。有什么线索是我做错了什么,或者图表选项中是否有设置可以正常工作?

另一件事是,我只能获得一个图表的值 - 我的鼠标所在的那个,我似乎无法获得十字准线所在的其余图表的值移动。

突出显示
if(item) {
    var x = item.datapoint[0].toFixed(2),
        y = item.datapoint[1].toFixed(2);
    console.log("x:" + x + ", " + "y:" + y);
}

仅当光标靠近某个点时有效(否则 item 为空)。

要获得离十字准线最近的点,您必须通过搜索最近的点并进行插值(对于每个图形)来手动突出显示。其代码可能如下所示:

var axes = value.getAxes();
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
    pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
    return;
}
$('#output').html("x: " + pos.x.toPrecision(2));

$.each(graphs, function(innerKey, innerValue) {
    var i, series = innerValue.getData()[0];

    // Find the nearest points, x-wise
    for (i = 0; i < series.data.length; ++i) {
        if (series.data[i][0] > pos.x) {
            break;
        }
    }

    // Now Interpolate
    var y,
        p1 = series.data[i - 1],
        p2 = series.data[i];

    if (p1 == null) {
        y = p2[1];
    } else if (p2 == null) {
        y = p1[1];
    } else {
        y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
    }

    $('#output').html($('#output').html() + "<br />" + "y (" + innerValue.getData()[0].label + "): " + y.toPrecision(2));

请参阅此 fiddle 以获取完整的工作示例。对新代码和 fiddle:

的一些评论
  • 有正弦和余弦值作为示例数据,因此使用浮点数,相应地更改为 int 数 and/or 日期值
  • 使用 <p> 元素而不是控制台进行输出
  • 如果需要,可以进一步优化寻点和插值代码(这里的基本版本取自 Flot 页面上的 example
  • 仅当每个图表只有一个数据系列时才有效