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