set axis limits in matplotlib pyplot


I have two subplots in a figure. I want to set the axes of the second subplot such that it has the same limits as the first subplot (which changes depending on the values plotted). Can someone please help me? Here is the code:

import matplotlib.pyplot as plt

plt.figure(1, figsize = (10, 20))
## First subplot: Mean value in each period (mean over replications)
plt.subplot(211, axisbg = 'w')
plt.plot(time,meanVector[0:xMax], color = '#340B8C', 
         marker = 'x', ms = 4, mec = '#87051B', markevery = (asp, 
plt.xticks(numpy.arange(0, T+1, jump), rotation = -45)
plt.axhline(y = Results[0], color = '#299967', ls = '--')
plt.ylabel('Mean Value')

## Second subplot: moving average for determining warm-up period
## (Welch method)
plt.plot(time[0:len(yBarWvector)],yBarWvector, color = '#340B8C')
plt.xticks(numpy.arange(0, T+1, jump), rotation = -45)
plt.xlim((0, T))

In the second subplot, what should be the arguments for plt.ylim() function? I tried defining

ymin, ymax = plt.ylim()

in the first subplot and then set


in the second subplot. But that did not work, because the returned value ymax is the maximum value taken by the y variable (mean value) in the first subplot and not the upper limit of the y-axis.

Thanks in advance.

9/5/2010 10:48:38 AM

Accepted Answer

I searched some more on the matplotlib website and figured a way to do it. If anyone has a better way, please let me know.

In the first subplot replace plt.subplot(211, axisbg = 'w') by ax1 = plt.subplot(211, axisbg = 'w') . Then, in the second subplot, add the arguments sharex = ax1 and sharey = ax1 to the subplot command. That is, the second subplot command will now look:

plt.subplot(212, sharex = ax1, sharey = ax1)

This solves the problem. But if there are other better alternatives, please let me know.

9/5/2010 11:01:26 AM

Your proposed solution should work, especially if the plots are interactive (they will stay in sync if one changes).

As alternative, you can manually set the y-limits of the second axis to match that of the first. Example:

from pylab import *

x = arange(0.0, 2.0, 0.01)
y1 = 3*sin(2*pi*x)
y2 = sin(2*pi*x)

ax1 = subplot(211)
plot(x, y1, 'b')

plot(x, y2, 'g')
ylim( ax1.get_ylim() )        # set y-limit to match first axis


alt text

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow