user8322222
user8322222

Reputation: 529

Setting a length to hover text in plotly-Dash Scatter plot

I have a scatter plot in Dash where the text property (sets text displayed on hover) is set to take the text from a certain column in the dataframe.

The problem is that some of the hover text is too long and goes off the page. Is there a way to give the hover length a fixed length so this doesn't happen?

I've seen this done using hoverformat for numerical data. But my hover information is text.

Upvotes: 1

Views: 1692

Answers (1)

Lawliet
Lawliet

Reputation: 1592

I'm not very sure if there is an attribute to set a fixed size to the hoverinfo, but you can always do some preprocessing with the text list before displaying it which is much easier and also customizable based on the needs.

Here is one way to do this,

import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objs as go
import json
import pandas as pd

app = dash.Dash()


#Consider this as the dataframe to be shown in hover
L = ["Text A", "Text B", "Text C", "Text D", "Text E"]
df = pd.DataFrame({'col':L})


# Here write your custom preprocessing function, 
# We can do whatever we want here to truncate the list
# Here every element in the list is truncated to have only 4 characters
def process_list(a):
    return [elem[:4] for elem in a]

app.layout = html.Div([
    dcc.Graph(
        id='life-exp-vs-gdp',
        figure={
            'data': [
                go.Scatter(
                    x = [1,2,3,4,5],
                    y = [2,1,6,4,4],
                    #call the pre processing function with the data frame
                    text = process_list(df['col']),
                    hoverinfo = 'text',
                    marker = dict(
                        color = 'green'
                    ),
                    showlegend = False
                )
            ],
            'layout': go.Layout(
            )
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

Upvotes: 5

Related Questions