python-3.x - 绘制来自 Pandas Agg 的阴影误差线

标签 python-3.x pandas matplotlib 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 |

我正在使用以下代码从该数据生成一个 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'])

输出:

Output Graph 这似乎是一个非常困惑的解决方案,并且实际上只会产生阴影输出,因为我有太多数据。从带有阴影错误区域的数据框中生成折线图的正确方法是什么?我看过 Plot yerr/xerr as shaded region rather than error bars ,但无法针对我的情况进行调整。

最佳答案

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

请允许我重新排列您的数据集,以便更轻松地加载到 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


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)

enter image description here

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

enter image description here

编辑

由于问题显然是在您的特定数据帧格式上迭代,让我展示您如何做到这一点(我是 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])

并且您应该能够对其进行迭代并获得相同的图:

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)

或者您可以将其重新堆叠为上面的格式

(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

关于python-3.x - 绘制来自 Pandas Agg 的阴影误差线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50627870/

相关文章:

python - 如何转义格式化 python 字符串中的单个反斜杠?

python - 通过在另一列 pandas 中拆分逗号分隔的多个值来复制行

python - 从pd数据帧到Excel的分层索引,需要转发填充和取消合并

python - 在pylab中更改图形窗口标题

python - 如何创建 3 列散点图

python - 根据 ID 值删除/保留 numpy 数组行

python - 我可以快速获得 python 列表中最内部子列表的最小长度吗?

python - 安装 Pandas 的问题 : "command ' llvm-gcc-4. 2' failed with exit status 1"

python - matplotlib 中是否有一个参数可以稍微调整条形图的指定位置?

python - Python 中的 4 个子图条形图