web-dev-qa-db-ja.com

matplotlib pyplotで軸の制限を設定する

図には2つのサブプロットがあります。 2番目のサブプロットの軸を、最初のサブプロットと同じ制限を持つように設定します(プロットされる値に応じて変化します)。誰か助けてくれますか?コードは次のとおりです。

_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)
_

2番目のサブプロットでは、plt.ylim()関数の引数は何ですか?定義してみた

_ymin, ymax = plt.ylim()
_

最初のサブプロットで設定します

_plt.ylim((ymin,ymax))
_

2番目のサブプロット。ただし、戻り値ymaxは、最初のサブプロットのy変数(平均値)がとる最大値であり、y軸の上限ではないため、うまくいきませんでした。

前もって感謝します。

24
Curious2learn

MatplotlibのWebサイトでさらに検索し、その方法を見つけました。誰かがより良い方法を持っているなら、私に知らせてください。

最初のサブプロットでplt.subplot(211, axisbg = 'w')ax1 = plt.subplot(211, axisbg = 'w')に置き換えます。次に、2番目のサブプロットで、引数sharex = ax1およびsharey = ax1サブプロットコマンド。つまり、2番目のサブプロットコマンドは次のようになります。

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

これにより問題が解決します。しかし、他のより良い選択肢があれば、教えてください。

12
Curious2learn

提案されたソリューションは、特にプロットがインタラクティブである場合に機能するはずです(プロットが変更されても同期は維持されます)。

別の方法として、2番目の軸の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()

alt text

14
Amro