Matplotlib - 在错误的子图中绘制变量
Matplotlib - 在错误的子图中绘制变量
我有两个变量,我希望在不同的子图中绘制它们的误差线。然而,它们都绘制在底部的子图中。如何使它们绘制在不同的子图中?\n
from pandas import DataFrame, date_range, Timedelta import numpy as np from matplotlib import pyplot as plt rng = date_range(start='2015-01-01', periods=5, freq='24H') df = DataFrame({'y':np.random.normal(size=len(rng))}, index=rng) y1 = df['y'] y2 = (y1*3) sd1 = (y1*2) sd2 = (y1*2) fig,(ax1,ax2) = plt.subplots(2,1,sharex=True) ax1.errorbar(y1.index, y1, yerr=sd1) ax2.errorbar(y2.index, y2, yerr=sd2) plt.show()
\n
问题原因:
在代码中,通过plt.subplots(2,1,sharex=True)
创建了两个子图ax1
和ax2
,然后分别将y1
和y2
绘制到了对应的子图上。但是在绘制y2
时,却使用了y1
的误差数据sd2
,导致了数据绘制到了错误的子图上。
解决方法:
修改代码,将sd2
改为y2
的误差数据sd1
,即将_ = y2.plot(yerr=sd2, ax=ax2)
修改为_ = y2.plot(yerr=sd1, ax=ax2)
。然后重新运行代码,即可得到正确的子图绘制。
解决后的代码如下:
from pandas import DataFrame, date_range, Timedelta import numpy as np from matplotlib import pyplot as plt rng = date_range(start='2015-01-01', periods=5, freq='24H') df = DataFrame({'y':np.random.normal(size=len(rng))}, index=rng) y1 = df['y'] y2 = (y1*3) sd1 = (y1*2) sd2 = (y1*2) fig,(ax1,ax2) = plt.subplots(2,1,sharex=True) _ = y1.plot(yerr=sd1, ax=ax1) _ = y2.plot(yerr=sd1, ax=ax2)
重新运行后,得到的输出结果为: