Ryan Halabi Ryan Halabi - 1 year ago 228
Javascript Question

Plotly.js Activate Hovertext

I'm using plotly to plot some points, if these points satisfy a condition I'd like the hoverinfo that plotly shows when you hover near the point to display.

desired pseudo code

z = {'x': x_val, 'y': y_val , 'type' : 'scatter' , 'mode' : 'markers',
'hoverinfo': 'text', 'hovermode' : 'closest'}
z['text'] = text

// check condition
if ( condition)
z['hovermode'] = 'on' //plotly doesn't have 'on' as a setting :(

Unfortunately the only options for hovermode appear to be: closest, x, y, and false.

Is there any way to activate hoverinfo? I know I could set mode = 'markers + text' but it isn't as pretty.

Answer Source

You can use the plotly_hover event and change the opacity of the hoverinfo which has the class hoverlayer. It has the inverse logic of what you are asking for, i.e. it hides undesirable hoverinfo, but it produces the same result.

In the snippet below only dots with an y-value of more than 2 have a hoverinfo.

var data = [
    x: [0, .5, 1, 1.5, 2],
    y: [1, 3, 2, 4, 2],
    mode: 'markers',
    marker: {size:16},
    text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
    type: 'scatter'
Plotly.newPlot('myDiv', data);

var myPlot = document.getElementById('myDiv');
myPlot.on('plotly_hover', function(data){
  var infotext = data.points.map(function(d){
    Plotly.d3.selectAll(".hoverlayer").style("opacity", (d.y > 2) ? 1: 0);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 100%; height: 500px;"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download