简体   繁体   English

如何从数据帧的折线图中 plot 误差条

[英]How to plot errorbar in line chart from dataframes

I have two dataframes, df_avg and df_sem, which contain mean values and standard errors of the means, respectively.我有两个数据框,df_avg 和 df_sem,它们分别包含平均值和平均值的标准误差。 For example:例如:

        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

and

        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

I want to plot a line chart using temp as the x-axis and the dataframe columns as the y-axes.我想 plot 使用 temp 作为 x 轴和 dataframe 列作为 y 轴的折线图。 I also want to use the df_sem dataframe to provide error bars for each line (note the column names are the same between the two dataframes).我还想使用 df_sem dataframe 为每一行提供误差线(注意两个数据帧之间的列名相同)。

I can achieve this with the following code: df_avg.plot(yerr=df_sem) , but this does not allow me to change many aspects of the plot, like DPI, labels, and things like that.我可以使用以下代码实现此目的: df_avg.plot(yerr=df_sem) ,但这不允许我更改 plot 的许多方面,例如 DPI、标签等。

So I've tried to make the plot using the following code as an alternative:因此,我尝试使用以下代码作为替代方案来制作 plot:

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

But this gives me the error: ValueError: shape mismatch: objects cannot be broadcast to a single shape但这给了我错误: ValueError: shape mismatch: objects cannot be broadcast to a single shape

How do I go about making the same chart that I am able to using pandas plotting with matplotlib plotting?我如何 go 制作与 pandas 绘图和 matplotlib 绘图相同的图表?

Thanks!谢谢!

You can do just a simple for loop:你可以做一个简单for循环:

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

plt.legend()

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM