Search code examples
pythonhoverplotlymapboxfigure

How to interact with plotly.figure_factory hover?


I tried the following code:

import plotly.io as pio
import plotly.express as px
import json
import pandas as pd
import plotly.graph_objects as go 
import plotly.figure_factory as ff
import plotly.express as px


df = px.data.carshare()

fig = go.Figure() 


app = dash.Dash()
#fac figurile
fig  = ff.create_hexbin_mapbox(df,lat = 'centroid_lat', lon = 'centroid_lon',nx_hexagon = 10,color = 'car_hours',
                               labels = {'color':'Point Count '},

                               opacity = 0.5)


fig.update_layout(mapbox_style="carto-darkmatter")
fig.update_layout(margin=dict(b=0, t=0, l=0, r=0))

fig.show()

And it displays: enter image description here

And I want to modify the hover so that it will only show me the float value with only the first decimal on hover and I also want to be able to display something after it displays the value. For example the value on the hover should be 'Point Count = 1019.9 cars per hour. Unfortunately, the documentation does not help very much.


Solution

  • It seems to me that your best option for ff.create_hexbin_mapbox would be to configure it directly through:

    fig.data[0].hovertemplate = 'Point Count =%{z:,.1f}<extra>Cars per hour</extra>'
    

    Which will turn this:

    enter image description here

    ... into this:

    enter image description here

    Complete code

    import plotly.io as pio
    import plotly.express as px
    import json
    import pandas as pd
    import plotly.graph_objects as go 
    import plotly.figure_factory as ff
    import plotly.express as px
    
    
    df = px.data.carshare()
    
    fig = go.Figure() 
    
    
    # app = dash.Dash()
    #fac figurile
    fig  = ff.create_hexbin_mapbox(df,lat = 'centroid_lat', lon = 'centroid_lon',nx_hexagon = 10,color = 'car_hours',
                                   labels = {'color':'Point Count '},
    
                                   opacity = 0.5)
    
    
    fig.update_layout(mapbox_style="carto-darkmatter")
    fig.update_layout(margin=dict(b=0, t=0, l=0, r=0))
    fig.data[0].hovertemplate = 'Point Count =%{z:,.1f}<extra>Cars per hour</extra>'
    fig.show()