Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split tick labels or wrap tick labels [duplicate]

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))
like image 362
juzcrap Avatar asked Oct 15 '25 09:10

juzcrap


1 Answers

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

like image 157
gehbiszumeis Avatar answered Oct 16 '25 22:10

gehbiszumeis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!