绘制 Pandas Agg 的阴影误差线

Lar*_*dor 3 matplotlib python-3.x pandas jupyter-notebook

我有以下格式的数据:

|      | Measurement 1 |      | Measurement 2 |      |
|------|---------------|------|---------------|------|
|      | Mean          | Std  | Mean          | Std  |
| Time |               |      |               |      |
| 0    | 17            | 1.10 | 21            | 1.33 |
| 1    | 16            | 1.08 | 21            | 1.34 |
| 2    | 14            | 0.87 | 21            | 1.35 |
| 3    | 11            | 0.86 | 21            | 1.33 |
Run Code Online (Sandbox Code Playgroud)

我使用以下代码从该数据生成 matplotlib 线图,该图将标准差显示为填充区域,如下所示:

def seconds_to_minutes(x, pos):
    minutes = f'{round(x/60, 0)}'
    return minutes

fig, ax = plt.subplots()
mean_temperature_over_time['Measurement 1']['mean'].plot(kind='line', yerr=mean_temperature_over_time['Measurement 1']['std'], alpha=0.15, ax=ax)
mean_temperature_over_time['Measurement 2']['mean'].plot(kind='line', yerr=mean_temperature_over_time['Measurement 2']['std'], alpha=0.15, ax=ax)

ax.set(title="A Line Graph with Shaded Error Regions", xlabel="x", ylabel="y")
formatter = FuncFormatter(seconds_to_minutes)
ax.xaxis.set_major_formatter(formatter)
ax.grid()
ax.legend(['Mean 1', 'Mean 2'])
Run Code Online (Sandbox Code Playgroud)

输出:

输出图 这看起来是一个非常混乱的解决方案,并且实际上只产生阴影输出,因为我有太多数据。从带有阴影错误区域的数据帧生成线图的正确方法是什么?我已经将Plot yerr/xerr 视为阴影区域而不是误差线,但无法根据我的情况进行调整。

fil*_*ppo 7

链接的解决方案有什么问题?看起来很简单。

请允许我重新排列您的数据集,以便更轻松地加载到 Pandas 中DataFrame

   Time  Measurement  Mean   Std
0     0            1    17  1.10
1     1            1    16  1.08
2     2            1    14  0.87
3     3            1    11  0.86
4     0            2    21  1.33
5     1            2    21  1.34
6     2            2    21  1.35
7     3            2    21  1.33
Run Code Online (Sandbox Code Playgroud)


for i, m in df.groupby("Measurement"):
    ax.plot(m.Time, m.Mean)
    ax.fill_between(m.Time, m.Mean - m.Std, m.Mean + m.Std, alpha=0.35)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这是一些随机生成的数据的结果:

在此输入图像描述

编辑

由于问题显然是在迭代您的特定数据帧格式,让我向您展示如何做到这一点(我是新手,pandas因此可能有更好的方法)。如果我正确理解你的屏幕截图,你应该有类似的内容:

Measurement    1          2      
            Mean   Std Mean   Std
Time                             
0             17  1.10   21  1.33
1             16  1.08   21  1.34
2             14  0.87   21  1.35
3             11  0.86   21  1.33

df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 4 entries, 0 to 3
Data columns (total 4 columns):
(1, Mean)    4 non-null int64
(1, Std)     4 non-null float64
(2, Mean)    4 non-null int64
(2, Std)     4 non-null float64
dtypes: float64(2), int64(2)
memory usage: 160.0 bytes

df.columns
MultiIndex(levels=[[1, 2], [u'Mean', u'Std']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=[u'Measurement', None])
Run Code Online (Sandbox Code Playgroud)

你应该能够迭代它并获得相同的图:

for i, m in df.groupby("Measurement"):
    ax.plot(m["Time"], m['Mean'])
    ax.fill_between(m["Time"],
                    m['Mean'] - m['Std'],
                    m['Mean'] + m['Std'], alpha=0.35)
Run Code Online (Sandbox Code Playgroud)

或者您可以将其重新排列为上面的格式

(df.stack("Measurement")      # stack "Measurement" columns row by row
 .reset_index()               # make "Time" a normal column, add a new index
 .sort_values("Measurement")  # group values from the same Measurement
 .reset_index(drop=True))     # drop sorted index and make a new one
Run Code Online (Sandbox Code Playgroud)