在matplotlib pyplot中设置轴限制

Cur*_*arn 24 python matplotlib

我在图中有两个子图.我想设置第二个子图的轴,使其具有与第一个子图相同的限制(根据绘制的值而变化).有人可以帮帮我吗?这是代码:

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)
Run Code Online (Sandbox Code Playgroud)

在第二个子图中,plt.ylim()函数的参数应该是什么?我尝试过定义

ymin, ymax = plt.ylim()
Run Code Online (Sandbox Code Playgroud)

在第一个子图中然后设置

plt.ylim((ymin,ymax))
Run Code Online (Sandbox Code Playgroud)

在第二个子图中.但这不起作用,因为返回值ymaxy第一个子图中变量(平均值)所采用的最大值,而不是y轴的上限.

提前致谢.

Amr*_*mro 14

您提出的解决方案应该有效,特别是如果这些图是交互式的(如果更改,它们将保持同步).

或者,您可以手动设置第二个轴的y限制以匹配第一个轴的y限制.例:

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()
Run Code Online (Sandbox Code Playgroud)

替代文字


Cur*_*arn 12

我在matplotlib网站上搜索了一些,并找到了一种方法.如果有人有更好的方法,请告诉我.

在第一个子图中替换plt.subplot(211, axisbg = 'w')ax1 = plt.subplot(211, axisbg = 'w') .然后,在第二个子图中,添加参数sharex = ax1sharey = ax1subplot命令.也就是说,第二个subplot命令现在将显示:

plt.subplot(212, sharex = ax1, sharey = ax1)
Run Code Online (Sandbox Code Playgroud)

这解决了这个问题.但如果有其他更好的选择,请告诉我.