使用setp在matplotlib紧密布局中包装长y标签

时间:2013-04-01 09:14:14

标签: python matplotlib

我一直试图在我的代码中为长标签包装文本。我尝试了之前建议的textwrap方法here,但我的代码通过使用pyplot.setp()方法从csv导入的数组定义了yticklabels。我使用tight_layout()进行格式化。

所以问题是 - 有没有办法将真正长y标签轻松包装到换行符?

以下是我想修复的示例代码:

import numpy as np
import matplotlib.pyplot as plt

labels=('Really really really really really really long label 1', 'Really really really really really really long label 2', 'Really really really really really really long label 3')
values=(30,50,40)

fig = plt.figure()
ax=fig.add_subplot(111)

plt.ylim((0,40))
for i in np.arange(3):
    plt.barh(15*i, values[i])

plt.yticks(15*np.arange(3))
plt.setp(ax.set_yticklabels(labels))

plt.tight_layout()
plt.show()

这就是这样的事情 enter image description here 我希望标签在固定宽度后转到换行符。有什么想法吗?

2 个答案:

答案 0 :(得分:39)

我尝试在标签上使用textwrap,它适用于我。

from textwrap import wrap
labels=['Really really really really really really long label 1',
        'Really really really really really really long label 2',
        'Really really really really really really long label 3']
labels = [ '\n'.join(wrap(l, 20)) for l in labels ]

在代码中插入此内容即可:

Wrapped labels

答案 1 :(得分:0)

如果您正在寻找一种动态包装标签的快速方法,只需将' '替换为'\n'即可,

wrapped_labels = [ label.replace(' ', '\n') for label in labels ]