Skip to main content
 首页 » 编程设计

python之matplotlib 上的常见 y 标签未调整

2025年05月04日25qq号

我有两个子图,并且希望两个子图有共同的 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 轴为中心。

请您参考如下方法:

使用文本:

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()