4

我目前正在用几个子图绘制(使用 Python-x,y 2.7.2.1),并且我希望将所有 y 标签放在一行中。目前它们不是,因为刻度标签有不同的大小。作为演示,我添加了这个脚本:

    import pylab as P
    import numpy as N

    x = N.linspace(0,2*N.pi,10000)
    y1 = N.sin(x)
    y2 = N.cos(x)*10000

    P.figure()
    ax1 = P.subplot(211)
    P.plot(x,y1,"k-")
    y1 = P.ylabel("$\\sin{(x)}$")
    P.xlim((0,2*N.pi))
    ax2 = P.subplot(212)
    P.plot(x,y2,"k--")
    y2 = P.ylabel("$\\cos{(x)}\\cdot{}10^4$")
    P.xlim((0,2*N.pi))
    P.show()

结果看起来像这样,请注意相对于彼此移动的标签:

两个相对于彼此具有移位标签的图

我试图通过使用设置标签位置

    (x,y) = y2.get_position()
    ax1.yaxis.set_label_coords(x,y)

但显然他们使用不同的坐标,因为 set_label_coords 需要相对坐标,而 get_position() 似乎会产生像素或其他东西。绝望尝试使用

    y1.set_x(x); y1.set_y(y)

没有任何效果。所以我对自己说:请教专家——我来了。谁能告诉我如何移动标签,使它们彼此对齐并且看起来像预期的那样棒?

我期待着你的回答。

4

2 回答 2

2

You can pad the position of the labels with

P.ylabel("$\\sin{(x)}$", labelpad=20)

and

P.ylabel("$\\cos{(x)}\cdot{}10^4$", labelpad=20)

with some adjustment, this should achieve what you desire. You can even set it after the plot with

ax.yaxis.labelpad = 20

The y label isn't correctly aligned as the length of the numbers on the y axis changes, and shifts the label position. You can fix the size of the number on the y axis with

from matplotlib.ticker import FuncFormatter

def thousands(x, pos):
    'The two args are the value and tick position'
    return '%4.1f' % (x*1e-3)

formatter = FuncFormatter(thousands)

ax = fig.add_subplot(211)
ax.yaxis.set_major_formatter(formatter)

This will guarantee that the length of the numbers on the y axis is always 4 characters, and so you can fix the offset of the y label for all values. Change the returned string in the thousands() function of this doesn't please you!

Edit

Yet another way to achieve this could be to hard code the position of your labels using set_label_coords

ax.yaxis.set_label_coords(0.5, 0.5)

I just spotted that method, and it might be of some use to you .. ! (0,0) is (left, bottom), (0.5, 0.5) is (middle, middle) etc.

于 2013-02-27T13:10:19.393 回答
1

正如 danodonovan 所说, set_label_coords 是一种可能的方法。我可能会补充一点,这个设置对我来说效果很好。

ax7.yaxis.set_label_coords(-0.2, 0.5)

“诀窍”是使用负数将标签移到绘图之外。

于 2013-03-13T17:50:12.597 回答