Matplotlib:将y标记向左对齐 [英] Matplotlib: Aligning y-ticks to the left

查看:196
本文介绍了Matplotlib:将y标记向左对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可变长度的刻度标签,我想将它们向左对齐(即,较短的标签和y轴之间有一个空格).有什么合理的方法可以做到这一点吗? 使用水平对齐方式向左"会将其向左对齐,但是它们都从轴开始,因此最终在绘图内.因此,另一个问题可能是-我可以更改其起点吗?

I have tick labels of variable length, and I want to align them to the left (i.e. to have a space between the shorter ones and the y axis). Is there any reasonable way to do this? Using horizontal alignment 'left' aligns them to the left, but they all start at the axis, so they end up inside the plot. So an alternative question could be - can I change their starting point?

演示代码:

import numpy as np
import matplotlib.pyplot as plt

ticks = ["Lorem ipsum dolor sit amet, consectetur adipisicin", "g elit, sed do",      "eiusmod tempor incididunt ut labo", "re et dolore magna ali", "qua. Ut en", "im ad minim veniam, quis nostr", "ud exercitation ullamco labo", "ris nisi ut aliquip ex ea c", "ommodo co", "nsequat. Duis aute irure dolor in rep"]
data = [5,1,2,4,1,4,5,2,1,5]
ind = np.arange(len(data))
fig = plt.figure()
ax = plt.subplot(111)
ax.barh(ind, data, 0.999)
ax.set_yticks(ind + 0.5)
r = ax.set_yticklabels(ticks)#, ha = 'left')
fig.set_size_inches(12, 8)
fig.savefig(r'C:\try.png', bbox_extra_artists=r, bbox_inches='tight')

推荐答案

您只需要添加pad.参见 matplotlib相对于轴的刻度位置

yax = ax.get_yaxis()
yax.set_tick_params(pad=pad)

(文档)

确定垫子应该是什么:

import numpy as np
import matplotlib.pyplot as plt

ticks = ["Lorem ipsum dolor sit amet, consectetur adipisicin", "g elit, sed do",      "eiusmod tempor incididunt ut labo", "re et dolore magna ali", "qua. Ut en", "im ad minim veniam, quis nostr", "ud exercitation ullamco labo", "ris nisi ut aliquip ex ea c", "ommodo co", "nsequat. Duis aute irure dolor in rep"]
data = [5,1,2,4,1,4,5,2,1,5]
ind = np.arange(len(data))
fig = plt.figure(tight_layout=True) # need tight_layout to make everything fit
ax = plt.subplot(111)
ax.barh(ind, data, 0.999)
ax.set_yticks(ind + 0.5)
r = ax.set_yticklabels(ticks, ha = 'left')
fig.set_size_inches(12, 8, forward=True) 
# re-size first, the shift needs to be in display units
plt.draw()  # this is needed because get_window_extent needs a renderer to work
yax = ax.get_yaxis()
# find the maximum width of the label on the major ticks
pad = max(T.label.get_window_extent().width for T in yax.majorTicks)

yax.set_tick_params(pad=pad)
plt.draw()

这篇关于Matplotlib:将y标记向左对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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