Matplotlib - 在错误的子图中绘制变量

10 浏览
0 Comments

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\"Example

0
0 Comments

问题原因:

在代码中,通过plt.subplots(2,1,sharex=True)创建了两个子图ax1ax2,然后分别将y1y2绘制到了对应的子图上。但是在绘制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)

重新运行后,得到的输出结果为:

enter image description here

0