python – 在分组后使用mean和std绘制错误栏

我有以下数据帧:

mean       std
insert quality                    
0.0    good     0.009905  0.003662
0.1    good     0.450190  0.281895
       poor     0.376818  0.306806
0.2    good     0.801856  0.243288
       poor     0.643859  0.322378
0.3    good     0.833235  0.172025
       poor     0.698972  0.263266
0.4    good     0.842288  0.141925
       poor     0.706708  0.241269
0.5    good     0.853634  0.118604
       poor     0.685716  0.208073
0.6    good     0.845496  0.118609
       poor     0.675907  0.207755
0.7    good     0.826335  0.133820
       poor     0.656934  0.222823
0.8    good     0.829707  0.130154
       poor     0.627111  0.213046
0.9    good     0.816636  0.137371
       poor     0.589331  0.232756
1.0    good     0.801211  0.147864
       poor     0.554589  0.245867

如果想要绘制2条曲线(点误差),使用索引列“插入”作为X轴并将两条曲线区分为“质量”[好,差],我该怎么办?它们也应该是不同的颜色.

我有点卡住,我制作了各种各样的情节.

解决方法

您可以循环遍历df.groupby(‘quality’)中的组,并在每个组上调用group.plot.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'insert': [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.0],'mean': [0.009905,0.45019,0.376818,0.801856,0.643859,0.833235,0.698972,0.842288,0.706708,0.853634,0.685716,0.845496,0.675907,0.826335,0.656934,0.829707,0.627111,0.816636,0.589331,0.801211,0.554589],'quality': ['good','good','poor','poor'],'std': [0.003662,0.281895,0.306806,0.243288,0.322378,0.172025,0.263266,0.141925,0.241269,0.118604,0.208073,0.118609,0.207755,0.13382,0.222823,0.130154,0.213046,0.137371,0.232756,0.147864,0.245867]})

fig,ax = plt.subplots()    # 1

for key,group in df.groupby('quality'):
    group.plot('insert','mean',yerr='std',label=key,ax=ax)   # 2

plt.show()

enter image description here

要使两个图显示在相同的轴上:

>创建自己的轴对象,ax.
>在每次调用group.plot时将ax参数设置为axes对象

它可能看起来像条形图更好:

# fill in missing data with 0,so the bar plots are aligned
df = df.pivot(index='insert',columns='quality').fillna(0).stack().reset_index()

colors = ['green','red']
positions = [0,1]

for group,color,pos in zip(df.groupby('quality'),colors,positions):
    key,group = group
    print(group)
    group.plot('insert',kind='bar',width=0.4,position=pos,color=color,alpha=0.5,ax=ax)

ax.set_xlim(-1,11)  
plt.show()

enter image description here

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...