views:

328

answers:

2

Hello,

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, 
                                                             2*asp))
plt.xticks(numpy.arange(0, T+1, jump), rotation = -45)
plt.axhline(y = Results[0], color = '#299967', ls = '--')
plt.ylabel('Mean Value')
plt.xlabel('Time')
plt.grid(True)


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

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

plt.ylim((ymin,ymax))

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.

+2  A: 

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.

Curious2learn
+1  A: 

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)

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

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

show()

alt text

Amro