我已经阅读了有关如何将subplot2grid与sharex,sharey轴一起使用的问题和答案。出于某种原因,ax.set_xlim被忽略了。我正在制作五个图,填充3 x 2子图阵列中的前五个位置。对于第一个图,我定义了x和y限制:
ax1.set_xlim([1.0, 2.3])
ax1.set_ylim([-40, 140])
对于第二个图,我使用sharex和sharey来使用ax1.set_xlim和ax1.set_ylim。当我以交互式,控制台模式运行代码并仅绘制第一个图时,使用定义的x和y限制。接下来,对于第二个图,使用sharex和sharey:
ax2 = plt.subplot2grid((3,2), (0,1), sharex = ax1, sharey = ax1)
此时,我检查
ax2.get_xlim()
(1.0, 2.3)
ax2.get_ylim()
(-40, 140)
限制匹配
ax1.set_xlim([1.0, 2.3])
ax1.set_ylim([-40, 140])
但是在执行第二个图的下一行代码时,
ax2.plot(x2,y, 'bo', label='Sensor 2')
xlim是不同的:
ax2.get_xlim()
(1.2, 2.2)
而不是
(1.0, 2.3)
如果我将代码作为脚本运行,那么两个图都使用了不受欢迎的xlim 1.2,2.2 以下是前两个图的代码:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.stats import linregress
x1 = np.array([1.592, 1.647, 1.699, 1.752, 1.793, 1.846, 1.900, 1.952, 2.033, 2.064, 2.113, 2.061, 2.008, 1.955, 1.906, 1.862, 1.808, 1.754, 1.701, 1.647, 1.594, 1.538, 1.482, 1.426, 1.373, 1.320, 1.266, 1.225, 1.267, 1.322, 1.376, 1.429, 1.487, 1.542])
x2 = np.array([1.617, 1.674, 1.726, 1.780, 1.822, 1.875, 1.929, 1.983, 2.036, 2.090, 2.143, 2.090, 2.037, 1.983, 1.933, 1.888, 1.833, 1.780, 1.726, 1.671, 1.617, 1.560, 1.503, 1.446, 1.391, 1.336, 1.282, 1.240, 1.282, 1.337, 1.392, 1.445, 1.502, 1.559])
y = np.array([32.12, 42.32, 51.83, 61.65, 69.10, 78.85, 88.51, 98.37, 108.13, 117.93, 127.68, 118.04, 108.32, 98.48, 89.45, 81.19, 71.40, 61.65, 51.86, 41.92, 32.23, 21.98, 11.66, 1.46, -8.34, -18.06, -27.78, -35.09, -27.79, -17.89, -8.29, 1.29, 11.43, 21.76])
# first plot
m, b=np.polyfit(x1,y,1) #x1 and y are 34 element vectors
ax1 = plt.gca()
ax1 = plt.subplot2grid((3,2), (0,0))
ax2 = plt.subplot2grid((3,2), (0,1), sharex = ax1, sharey = ax1)
ax1.plot(x1,y, 'bo', label='Sensor 1')
ax1.set_xlim([1, 2.3])
ax1.set_ylim([-40, 140])
ax1.grid(True)
ax1.set_title('Sensor 1')
ax1.plot(x1,m*x1+b,'b-')
# second plot
m, b=np.polyfit(x2,y,1)
#if ax2 is defined in this code section, (commented out), then a default ax
#is defined and overides ax1.set.lim and ax1.set.lim in code above
#ax2 = plt.subplot2grid((3,2), (0,1), sharex = ax1, sharey = ax1)
ax2.plot(x2,y, 'bo', label='Sensor 2')
ax2.grid(True)
ax2.set_title('Sensor 2')
ax2.plot(x2,m*x2+b,'b-')
plt.show()
不确定我错过了什么。谢谢你的任何建议。
答案 0 :(得分:0)
当ax2定义直接遵循ax1定义时,则sharex和sharey工作为ax2:
ax1 = plt.subplot2grid((3,2), (0,0))
ax2 = plt.subplot2grid((3,2), (0,1), sharex = ax1, sharey = ax1)