4

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))
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
juzcrap
  • 43
  • 1
  • 3

1 Answers1

6

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

enter image description here

gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41