I have read the questions and answers on how to use subplot2grid with sharex, sharey axes. For some reason, ax.set_xlim is being ignored. I am making five plots, populating the first five positions in a 3 x 2 subplot array. For the first plot, I define the x and y limits:
ax1.set_xlim([1.0, 2.3])
ax1.set_ylim([-40, 140])
For the second plot, I use sharex and sharey to use the ax1.set_xlim and ax1.set_ylim. When I run the code in interactive, console mode and only plot the first plot, the defined x and y limits are used. Next, for the second plot, use sharex and sharey:
ax2 = plt.subplot2grid((3,2), (0,1), sharex = ax1, sharey = ax1)
At this point, when I check
ax2.get_xlim()
(1.0, 2.3)
ax2.get_ylim()
(-40, 140)
the limits match
ax1.set_xlim([1.0, 2.3])
ax1.set_ylim([-40, 140])
But on executing the next line of code for the second plot,
ax2.plot(x2,y, 'bo', label='Sensor 2')
xlim is different:
ax2.get_xlim()
(1.2, 2.2)
and not
(1.0, 2.3)
If I run the code as a script, then both plots use the undesired xlim of 1.2, 2.2 Here is the code for the first two plots:
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()
Not sure what I am missing. Thanks for any suggestions.
x1andy? - Paul H