简体   繁体   English

在plotly-dash散点图中设置长度来悬停文本

[英]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. 我在Dash中有一个散点图,其中的text属性(设置了悬停时显示的文本)被设置为从数据框中的特定列获取文本。

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. 我已经看到使用hoverformat来处理数字数据。 But my hover information is text. 但是我的悬停信息是文本。

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. 我不太确定是否有一个属性可以为hoverinfo设置一个固定的大小,但是您始终可以在显示文本列表之前对文本列表进行一些预处理,这更加容易并且可以根据需要进行自定义。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM