拆分刻度标签或包装刻度标签 [英] split tick labels or wrap tick labels
问题描述
我有很长的绘图刻度标签,不幸的是我无法缩短.因此,我正在寻找将标签拆分为多行(换行文本)的代码.我尝试了自动换行,但它在我的代码中导致了错误.在 rotation=0
处设置刻度标签会使刻度标签相互重叠并变得不可读.
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.
我也尝试过使用 rotation = 90
,但是刻度标签却溢出到我的图表空间中.
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
是要走的路.函数 textwrap.fill()
更精确.您尚未发布收到的错误消息,但我确实假设您将整个数组 labels
传递给了 fill()
,这将导致错误消息.改用列表理解将每个单独的标签传递给 fill()
并且它会起作用.
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)
给予
这篇关于拆分刻度标签或包装刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!