![](/img/trans.png)
[英]Flot Chart Crosshair Plugin with multiple charts and dynamic legend
[英]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));
請參閱此小提琴,了解完整的工作示例。 對新代碼和小提琴的一些評論:
<p>
元素代替控制台輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.