y标签包装在matplotlib紧密布局中

y标签包装在matplotlib紧密布局中

本文介绍了使用setp将long y标签包装在matplotlib紧密布局中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在代码中将长标签的文本换行.我尝试了此处建议的textwrap方法,但是我的代码通过使用pyplot.setp()方法从csv导入的数组.我正在使用tight_layout()进行格式化.

I've been trying to wrap text for long labels in my code. I tried the textwrap method suggested earlier here, but my code defines yticklabels through an array imported from a csv using the pyplot.setp() method. I'm using tight_layout() for the formatting otherwise.

所以问题是-是否可以轻松地将y长的标签包装到换行符上?

So the question is - is there a way to wrap the really long y labels to newlines easily?

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

Here is some sample code that I'd like a fix for:

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()

这会绘制出类似这样的图形我希望标签在固定宽度后转到换行符.有什么想法吗?

This plots something like thisI'd like the labels to go to newlines after a fixed width. Any ideas?

推荐答案

我尝试在标签上使用textwrap,它对我有用.

I have tried using textwrap on the labels and it works for me.

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 ]

在您的代码中插入此代码即可:

Inserting this in your code gives us:

这篇关于使用setp将long y标签包装在matplotlib紧密布局中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:09