使用 setp 在 matplotlib 紧密布局中包装长 y 标签 [英] Wrapping long y labels in matplotlib tight layout using setp

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

问题描述

我一直试图在我的代码中为长标签包装文本.我尝试了之前建议的 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 this I'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 = [ '
'.join(wrap(l, 20)) for l in labels ]

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

Inserting this in your code gives us:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆