Search code examples
pythonplotlyvisualizationplotly-express

Is there a way that we can increase the size of the hover label in plotly express


I was trying to make a scatter mapbox using plotly express on the data of haunted places .The dataset has an attribute 'description' which is a multi line string. The problem is that most of the time where the string is too big it cuts off from left and right of the window just like this example: map Screenshot

Is there any way which I can change the code such that the description can be displayed on multiple lines instead of a single line.

Here is the code I used:

import numpy as np
import pandas as pd
import plotly.express as px

df = pd.read_csv(r"C:\Users\devas\Downloads\haunted_places.csv")

fig = px.scatter_mapbox(
    df,  # Our DataFrame
    lat='latitude',
    lon='longitude',
    width=1920,  # Width of map
    height=1080,  # Height of map
    hover_data=["description"],  # Display price when hovering mouse over house
    zoom=5
)

# Customize the hoverlabel
fig.update_layout(hoverlabel=dict(bgcolor="white", font=dict(size=12, family="Arial", color="black"),
                                  align="left"))

# Set the center of the map to the USA
fig.update_layout(mapbox_style="open-street-map",mapbox_center={"lat": 39.8283, "lon": -98.5795})

# Display the figure
fig.show()

I tried to fiddle with the update_layout and update_traces functions but couldn't get it right.


Solution

  • We approached your state by looking for similar data from the reference and concatenating the description column with strings from the other columns. The technique is to use the ability to break a line at any length of string, and furthermore, since html tags are valid for annotations, I added a new column with the string concatenated with the line break tag. The added column is designated as hover data.

    import numpy as np
    import pandas as pd
    import plotly.express as px
    import textwrap
    
    #df = pd.read_csv(r"C:\Users\devas\Downloads\haunted_places.csv")
    us_cities = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
    us_cities['description'] = (us_cities['City']+us_cities['State'])*20
    us_cities['description2'] = ['<br>'.join(textwrap.wrap(x, width=30)) for x in us_cities['description']]
    
    fig = px.scatter_mapbox(
        us_cities,
        lat='lat',
        lon='lon',
        width=1920, 
        height=1080,
        hover_data=['description2'],
        zoom=5
    )
    
    # Customize the hoverlabel
    fig.update_layout(hoverlabel=dict(bgcolor="white",
                                      font=dict(size=12, family="Arial", color="black"),
                                      align="left"))
    
    # Set the center of the map to the USA
    fig.update_layout(mapbox_style="open-street-map",mapbox_center={"lat": 39.8283, "lon": -98.5795})
    
    # Display the figure
    fig.show()
    

    enter image description here