Ploty legned - break line / fixed width

Hi all,

I am trying to have a fixed legend width in plotly express but unable to do so.

Sometimes I have very long stings in legend that I would like to break in multiple lines. The best way would be if they can be broke into multiple lines automatically based on the setting for legend box width since I don’t know the string length in advance.

Any way to achieve that? I tried ‘itemwidth’ but this doesn’t work.

I’m not aware of such functionality.

You can add breaks to the strings in the data you’re using to plot where you define where to insert <br> in the string based on the length of the string and the number of words.

If you’re plotting line charts it could be better to use lines with arrows to label the traces.

Example for legend with line breaks


import plotly.graph_objects as go


x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 17, 20]

# Create traces for each line
trace = go.Scatter(x=x, y=y, mode='lines', name='Legend<br>with<br>Line<br>Breaks')


layout = go.Layout(showlegend=True)


fig = go.Figure(data=[trace], layout=layout)


fig.show()

newplot

1 Like

Thanks, I solved it with your help and function that breaks line if string is longer than 40 chr:

        def insert_break_after_40(text):
            if len(text) <= 40:
                return text
            # If the text is longer, find the first space after the 40th character
            else:
                space_index = text.find(' ', 40)
                if space_index == -1:
                    return text
                return text[:space_index] + '<br>' + text[space_index+1:]
2 Likes

This is perfect! Thank you!