如何从数据框中绘制折线图中的错误栏

How to plot errorbar in line chart from dataframes

我有两个数据框,df_avg 和 df_sem,分别包含均值和均值的标准误差。例如:

        KPCmb1      KPCmb1IA    KPCmb2      KPCmb3      KPCmb4      KPCmb5      KPCmb6
temp                            
19.99   15.185905   24.954296   22.610052   29.249107   26.151815   34.374257   36.589218
20.08   15.198452   24.998227   22.615342   29.229325   26.187794   34.343738   36.596730
20.23   15.208917   25.055061   22.647499   29.234424   26.193382   34.363549   36.580033
20.47   15.244485   25.092773   22.691421   29.206816   26.202425   34.337385   36.640839
20.62   15.270921   25.145798   22.720752   29.217821   26.235101   34.364162   36.600030

        KPCmb1      KPCmb1IA    KPCmb2      KPCmb3      KPCmb4      KPCmb5      KPCmb6
temp                            
19.99   0.342735    0.983424    0.131502    0.893494    1.223318    0.536450    0.988185
20.08   0.347366    0.983732    0.136239    0.898661    1.230763    0.534779    0.993970
20.23   0.348641    0.981614    0.134729    0.898790    1.227567    0.529240    1.005609
20.47   0.350937    0.993973    0.138411    0.881142    1.237749    0.526841    0.991591
20.62   0.345863    0.983064    0.132934    0.883863    1.234746    0.533048    0.987520

我想绘制一个折线图,使用温度作为 x 轴,数据框列作为 y 轴。我还想使用 df_sem 数据框为每一行提供误差线(注意两个数据框之间的列名相同)。

我可以用下面的代码实现这个: df_avg.plot(yerr=df_sem),但这不允许我更改情节的许多方面,例如 DPI、标签等。

所以我尝试使用以下代码作为替代来制作情节:

plt.figure()
x = df_avg.index
y = df_avg
plt.errorbar(x,y,yerr=df_sem)
plt.show()

但这给了我错误:ValueError: shape mismatch: objects cannot be broadcast to a single shape

如何制作我能够使用 pandas 绘图和 matplotlib 绘图的相同图表?

谢谢!

你可以做一个简单的 for 循环:

for col in df_avg.columns:
    plt.errorbar(df_avg.index, df_avg[col], yerr=df_sem[col], label=col)

plt.legend()

输出: