调整matplotlib图形周围的页边距(使用换行的xticks或yticks标签)

2024-05-15 03:58:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在matplotlib中创建一个包含一些相当长的记号标签的图形。为了将标签放在合理的空间中,我尝试使用matplotlib中提供的包装:

plt.yticks([1],[a],wrap=True)

This works(output),但是勾号标签文本会延伸到图形的边缘。当文字设为换行时,如何在地物边缘和记号标签文字之间放置边距?在

失败的尝试:

I tried to create the desired margin by expanding the bounding box(output)

^{pr2}$

但是,换行改为将文本重新分配到新的地物边缘。在

完整示例:

import matplotlib.pyplot as plt

labeltext = "This is a really long string that I'd rather have wrapped so that it"\
    " doesn't go outside of the figure, but if it's long enough it will go"\
    " off the top or bottom!"

a4_width =  8.27
a4_height = 11.69 

f = plt.figure()
plt.ylim([0,2])
plt.xlim([0,2])
plt.yticks([1],[labeltext],wrap=True)

f.set_size_inches(a4_width, a4_height)
plt.subplots_adjust(left=0.3) #leave space on left for large yticklabel


#  outputs full page, yticklabel text to edge
f.savefig("nomargin.pdf")

#  tried to expand bounding box to create margin, 
#  but yticklabel then rewraps to fills space to edge
f.savefig("stillnomargin.pdf",bbox_inches=f.bbox_inches.expanded(2,2))

Tags: thetotrue图形matplotlibitplt标签

热门问题