Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set axis limits in matplotlib pyplot

Tags:

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.

like image 691
Curious2learn Avatar asked Sep 05 '10 10:09

Curious2learn


People also ask

How do I change the axis range in MatPlotLib?

MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.

How do I limit in MatPlotLib?

MatPlotLib with Python Matplotlib automatically arrives at the minimum and maximum values of variables to be displayed along x, y (and z axis in case of 3D plot) axes of a plot. However, it is possible to set the limits explicitly by using set_xlim() and set_ylim() functions.

How do you set Y Lim?

Set y-Axis Limits for Specific AxesCall the tiledlayout function to create a 2-by-1 tiled chart layout. Call the nexttile function to create the axes objects ax1 and ax2 . Plot data into each axes. Then set the y-axis limits for the bottom plot by specifying ax2 as the first input argument to ylim .


1 Answers

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

like image 188
Amro Avatar answered Oct 27 '22 18:10

Amro