38

我一直在尝试在我的代码中包装长标签的文本。我尝试了此处之前建议的 textwrap 方法,但我的代码通过使用该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()

这绘制了这样 在此处输入图像描述 的东西我希望标签在固定宽度后转到换行符。有任何想法吗?

4

2 回答 2

59

我试过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 ]

在你的代码中插入这个给我们:

包装标签

于 2013-04-01T09:18:18.310 回答
3

如果您正在寻找一种快速动态包装标签的方法,您可以像这样简单地' '替换'\n'

wrapped_labels = [ label.replace(' ', '\n') for label in labels ]
于 2020-06-22T19:06:07.120 回答