Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Created July 23, 2024 21:15
Show Gist options
  • Save jmbarbone/7751e03a156b216a7434705617fc6135 to your computer and use it in GitHub Desktop.
Save jmbarbone/7751e03a156b216a7434705617fc6135 to your computer and use it in GitHub Desktop.
I just want to move the legend to the cursor position....
library(plotly)
library(htmlwidgets)
x_unified_y_cursor <- "
// hovermode is 'x unified' but we don't want the default y/vertical
// positioning of the hover label. We want the hoverlabel to appear at the
// current cursor position (i.e. the y position of the cursor)
function(el) {
el.on('plotly_hover', function(data) {
console.log('event data: ', data);
// print legend
var legend = document.getElementsByClassName('hoverlayer')[0].getElementsByClassName('legend')[0];
legend.i
console.log('Legend: ', legend);
var text = '\"translate(' + data.event.x + ',' + data.event.y + ')\"';
document.getElementsByClassName('hoverlayer')[0].getElementsByClassName('legend')[0] = legend;
// get the element id of the legend
function getDomPath(el) {
var stack = [];
while ( el.parentNode != null ) {
console.log(el.nodeName);
var sibCount = 0;
var sibIndex = 0;
for ( var i = 0; i < el.parentNode.childNodes.length; i++ ) {
var sib = el.parentNode.childNodes[i];
if ( sib.nodeName == el.nodeName ) {
if ( sib === el ) {
sibIndex = sibCount;
}
sibCount++;
}
}
if ( el.hasAttribute('id') && el.id != '' ) {
stack.unshift(el.nodeName.toLowerCase() + '#' + el.id);
} else if ( sibCount > 1 ) {
stack.unshift(el.nodeName.toLowerCase() + ':eq(' + sibIndex + ')');
} else {
stack.unshift(el.nodeName.toLowerCase());
}
el = el.parentNode;
}
return stack.slice(1); // removes the html element
}
var id = getDomPath(legend);
console.log('I NEED SOME ID: {' + id + '}')
var update = {
transform: text
};
console.log('update: ', update);
Plotly.relayout(id, update);
});
}
"
plot_ly(
name = "reference",
type = "scatter",
mode = "lines+markers",
x = 1:5
) |>
add_trace(
name = "foo",
y = c(2.02, 1.63, 6.83, 4.84, 4.73)
) |>
add_trace(
name = "bar",
y = c(3.02, 2.63, 4.83 ,3.84, 1.73)
) |>
layout(
hovermode = "x unified"
) |>
# make tooltip hover at cursor location
htmlwidgets::onRender(x_unified_y_cursor) |>
# plotly_json() |>
force()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment