I have pretty long plot tick labels which unfortunately I cannot shorten. I am thus looking for a code to split the label into multiple lines (wrap text). I tried text wrap but it caused an error in my code.
Having the tick label at rotation=0
makes the tick label overlap each other and becomes un-readable.
I also tried having a rotation=90
but the tick label instead spills into my chart space.
plt.title(param)
plt.ylabel('Measurement')
plt.xticks(x_axis, labels, rotation = 10, fontsize=8, horizontalalignment="center")
plt.tick_params(axis='x', pad=6)
lgd = ax.legend(loc = 'upper left', bbox_to_anchor=(1,1))
textwrap
is the way to go. More precise the function textwrap.fill()
. You haven't posted the error message you got, but I do assume you passed the whole array labels
to fill()
which will cause an error message. Use list comprehension instead to pass each individual label to fill()
and it will work.
x_axis=range(5)
labels = ['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'] * len(x_axis)
plt.title('param')
plt.ylabel('Measurement')
# Note list comprehension in the next line
plt.xticks(x_axis, [textwrap.fill(label, 10) for label in labels],
rotation = 10, fontsize=8, horizontalalignment="center")
plt.tight_layout() # makes space on the figure canvas for the labels
plt.tick_params(axis='x', pad=6)
gives
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With