【问题标题】:Common y label on matplotlib not adjustingmatplotlib 上的常见 y 标签未调整
【发布时间】:2016-06-10 07:43:06
【问题描述】:

我有两个子图,希望两者都有共同的 x 轴和 y 轴标签。我的代码如下:

fig, ax = plt.subplots()
ax = fig.add_subplot(111)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax.set_ylabel("array2 stuff")

plt.subplot(2, 1, 1)
plt.plot(array1, array2, 'o-', label='stuff')
plt.title("my stuff")

plt.legend(loc="lower left")
plt.grid()

plt.subplot(2, 1, 2)
plt.plot(array1, array2, 'o-', label='stuff')
plt.xlabel("Date")
ax.set_ylabel("array2 stuff")
plt.legent(loc="lower left")
plt.ylim(-constant, constant)
plt.grid()

plot.show()

x 轴标签似乎有效,但 y 轴标签不会在两个图之间居中。相反,它以下部图的 y 轴为中心。

【问题讨论】:

    标签: python matplotlib plot subplot


    【解决方案1】:

    使用text:

    import matplotlib.pyplot as plt
    import numpy as np
    
    array1 = np.linspace(-10,10,10)
    array2 = np.linspace(-10,10,10)
    
    fig = plt.figure()
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212)
    
    plt.subplot(2, 1, 1)
    plt.plot(array1, array2, 'o-', label='stuff')
    plt.title("my stuff")
    
    plt.legend(loc="lower left")
    plt.grid()
    
    plt.subplot(2, 1, 2)
    plt.plot(array1, array2, 'o-', label='stuff')
    plt.xlabel("Date")
    plt.legend(loc="lower left")
    constant = 10
    plt.ylim(-constant, constant)
    plt.grid()
    fig.text(.05, .5, 'array stuff', ha='center', va='center', rotation='vertical')
    
    plt.show()
    

    【讨论】:

    • 谢谢你。虽然我正在寻找的只是一个 ylabel,但这对情节和居中都很常见。看看我的代码,有什么想法我出错了吗? "ax.set_ylabel("array2 stuff")" 不起作用(不是 "ax",也不是 "ax1" 或 "ax2"。
    • 好的,我为常用标签添加了一个文本对象。往上看。
    • 这正是我想要的。谢谢!