Search code examples
pythonplotlyline

plotly line color how to deal with long text in group color?


I am having a problem with plotly with group with long text label with this sample code

import pandas as pd
import plotly.express as px

df = pd.DataFrame(dict(
x =     [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4],
group = ["a", "Very longgggggggggggggggggggggggggggggggggggggggggggggg labelllllllllllllllllllllllllllllllllllllllllll", "c", "a", "Very longgggggggggggggggggggggggggggggggggggggggggggggg labelllllllllllllllllllllllllllllllllllllllllll", "c", "a", "b", "c", "a", "Very longgggggggggggggggggggggggggggggggggggggggggggggg labelllllllllllllllllllllllllllllllllllllllllll", "c"],
y =     [1, 2, 5, 3, 4, 5, 5, 6, 5, 7, 8, 5]
))
fig_sample = px.line(df, x="x", y="y",color='group',title='sample')
fig_sample .show()

The image show label group color have long description

As you can see are there any solution to plot color line without include text describe or only add line color but add text description only when mouse hover on graph ?


Solution

  • To display only the hover text, use a graph object and draw each group using the line mode of a scatter plot. Add custom data and specify the group columns of the data frame you have added to the hover template. However, the hovered text boxes are ugly. It is up to you to decide if you want to employ this method. Also, to deal with the long strings in the legend, the first graph removes the string, the second graph omits it by the number of characters, and the third method is to display all the long strings with line breaks at any number of characters. To split a long string, a string of 2 or more characters is split into 9-character units and rejoined with
    .

    import plotly.graph_objects as go
    
    fig = go.Figure()
    
    for g in df['group'].unique():
        dff = df.query('group == @g')
        legend_item = ['<br>'.join([x[i:i+9] for i in range(0,len(x),9)]) if len(x) >= 2 else x for x in dff['group'].unique()]
        fig.add_trace(go.Scatter(x=dff['x'],
                                 y=dff['y'], 
                                 mode='lines',
                                 customdata=dff, 
                                 hovertemplate='group:%{customdata[1]}',
                                 name=legend_item[0]))
    
    fig.update_layout(height=500)
    fig.show()
    

    enter image description here