This issue has plagued me in different charts for a long time. I recently discovered this same solution through a much later post on Stack Overflow, but credit where credit is due to @eliasdabbas, who came up with it two years earlier.
Given my struggles with implementing effective word wrap in different layouts and for different types of charts, I wanted to highlight how easily you can use this solution this to wrap any chart text:
import textwrap
def customwrap(s,width=30):
return "<br>".join(textwrap.wrap(s,width=width))
Example:
Here is a basic 100 % stacked bar chart:
It may be a matter of taste, but to me, the labels are too long and the chart is too squished. Simply add the above function and adjust the width until you get something that works:
import plotly
import plotly.express as px
import pandas as pd
import textwrap
cat = ['Some Text','Some Text','Some Text','Some Text',
'Some Longer Text','Some Longer Text','Some Longer Text','Some Longer Text',
'Some Even Longer Text','Some Even Longer Text','Some Even Longer Text','Some Even Longer Text',
'The Longest Text You Have Ever Seen','The Longest Text You Have Ever Seen','The Longest Text You Have Ever Seen','The Longest Text You Have Ever Seen']
val = [20,30,45,5,60,20,10,10,30,30,30,10,20,30,40,10]
rat = ['Great','Good','Average','Bad',
'Great','Good','Average','Bad',
'Great','Good','Average','Bad',
'Great','Good','Average','Bad']
test_list = [list(row) for row in zip(cat, val, rat)]
data = pd.DataFrame(test_list, columns=['Category', 'Value', 'Rating'])
def customwrap(s,width=16):
return "<br>".join(textwrap.wrap(s,width=width))
colors = plotly.colors.qualitative.Prism
fig = px.bar(
x= data['Value'],
y = data['Category'].map(customwrap),
color=data['Rating'],
barmode='stack',
orientation="h",
color_discrete_sequence=colors,
height=300,
width=400
)
fig.update_layout(
font_family="Open Sans, sans-serif",
font_color="steelblue",
font_size=8,
)
fig.show()
Result: