如何将错误栏添加到Matplotlib线图? [英] How to add Error Bar to Matplotlib line plot?
问题描述
我有以下用于绘制线图的数据集。该图以从数据中获得的值的平均值
的形式获得。我想在该图中添加误差条,以显示标准偏差。我查找了不同的答案,但在大多数答案中,他们明确定义了 x
和 y
,但是在这里我计算直接从数据框中绘制图。如何向该图添加误差线?
数据框df
UserId |日期| -7 | -6 | -5 | -4 | -3 | -2 | -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
1 2009-10-17 17: 38:32.590 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0
2 2009-10-19 00:37:23.067 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0
3 2009-10-20 08:37:14.143 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
4 2009-10-21 18:07:51.247 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | b
5 2009-10-22 21:25:24.483 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
代码
徽章= [ A, B, C]
用于徽章的徽章:
res.iloc [:,2:]。mean()。plot(kind ='line',label = badge)
输出
I have the following dataset which I use to plot a line plot. The plot is obtained as the mean
of values obtained from the data. I want to add error bars to this plot which shall show the standard deviation. I have looked up to different answers but in most of them they had defined x
and y
explicitly, but here I calculate the plot directly from the dataframe. How to add error bar to this plot?
Dataframe df
UserId | date |-7|-6|-5|-4|-3|-2|-1|0 |1 |2 |3 |4 |5 |6 |7
1 2009-10-17 17:38:32.590 |0 |0 |0 |0 |0 |0 |1 |0 |1 |0 |0 |0 |0 |0 |0
2 2009-10-19 00:37:23.067 |0 |0 |0 |0 |0 |1 |1 |0 |1 |0 |0 |0 |0 |0 |0
3 2009-10-20 08:37:14.143 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
4 2009-10-21 18:07:51.247 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
5 2009-10-22 21:25:24.483 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0
Code
badges = ["A", "B", "C"]
for badge in badges:
res.iloc[:,2:].mean().plot(kind='line', label = badge)
Output
EDIT (Plot for only one graph with Standard Deviation)
res.iloc[:,2:].mean().plot(kind='line', label = 'A')
plt.errorbar(x = res.columns.values[:-1], y = res.iloc[:,2:].mean(),yerr = res.iloc[:,2:].std())
Executing this code produces the following error:
TypeError: 'value' must be an instance of str or bytes, not a int
If you want to create your lines & error bars in the loop, you can use the plt.errorbar()
as normal inside the loop, but using seaborn
is a lot easier if you can get your data in the appropriate format.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.concat([
pd.DataFrame(np.random.randint(0,2, (5, 14))).assign(badge="A"),
pd.DataFrame(np.random.randint(0,2, (5, 14))).assign(badge="B"),
])
plt.figure(figsize=(10, 5))
badges = ["A", "B"]
colors = ["teal", "firebrick"]
for i, badge in enumerate(badges):
sub_df = df[df["badge"]==badge]
sub_df.iloc[:,:-1].mean().plot(kind='line', label=badge, color=colors[i])
plt.errorbar(
sub_df.columns.values[:-1] + (i*0.1), # offset the second error bar a bit
sub_df.iloc[:,:-1].mean(),
yerr=sub_df.iloc[:,:-1].std(),
fmt='|', ecolor='grey', elinewidth=1
);
这篇关于如何将错误栏添加到Matplotlib线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!