matplotlib 向左对齐y标记

zpgglvta  于 2023-05-23  发布在  其他
关注(0)|答案(2)|浏览(152)

我有可变长度的刻度标签,我想将它们向左对齐(即以在较短的两个和y轴之间具有空间)。有没有合理的方法来做到这一点?使用水平对齐'左'将它们向左对齐,但它们都从轴开始,因此它们最终在图中结束。所以另一个问题可能是-我能改变他们的出发点吗?

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')
chhqkbe1

chhqkbe11#

python 3.11.2matplotlib 3.7.1中测试

您只需要添加一个pad。参见matplotlib标记相对于轴的位置

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

matplotlib.axis.Axis.set_tick_params
要计算垫应该是什么:

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

yax = ax.get_yaxis()
# find the maximum width of the label on the major ticks
pad = max(T.label1.get_window_extent().width for T in yax.majorTicks)

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

vs3odd8k

vs3odd8k2#

有一个简单的方法可以通过使用mpl_toolkits来实现您的目标。

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist

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,axes_class=axisartist.Axes)  # Needs to specify axes_class
ax.barh(ind, data, 0.999)
ax.set_yticks(ind + 0.5)
r = ax.set_yticklabels(ticks)

ax.axis["left"].major_ticklabels.set_ha("left") # Then it's simple to use set_ha.

plt.show()

相关问题