使用 Seaborn FacetGrid 从数据框中绘制错误条 [英] Plotting errors bars from dataframe using Seaborn FacetGrid
问题描述
我想从 Seaborn FacetGrid 上的 Pandas 数据框中的一列绘制误差线
I want to plot error bars from a column in a pandas dataframe on a Seaborn FacetGrid
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar']*2,
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
df
示例数据框
A B C D
0 foo one 0.445827 -0.311863
1 bar one 0.862154 -0.229065
2 foo two 0.290981 -0.835301
3 bar three 0.995732 0.356807
4 foo two 0.029311 0.631812
5 bar two 0.023164 -0.468248
6 foo one -1.568248 2.508461
7 bar three -0.407807 0.319404
此代码适用于固定大小的误差线:
This code works for fixed size error bars:
g = sns.FacetGrid(df, col="A", hue="B", size =5)
g.map(plt.errorbar, "C", "D",yerr=0.5, fmt='o');
但我无法使用数据帧中的值使其工作
But I can't get it to work using values from the dataframe
df['E'] = abs(df['D']*0.5)
g = sns.FacetGrid(df, col="A", hue="B", size =5)
g.map(plt.errorbar, "C", "D", yerr=df['E']);
或
g = sns.FacetGrid(df, col="A", hue="B", size =5)
g.map(plt.errorbar, "C", "D", yerr='E');
两者都会产生错误
在阅读大量 matplotlib 文档和各种 stackoverflow 答案之后,这是一个纯 matplotlib 解决方案
After lots of matplotlib doc reading, and assorted stackoverflow answers, here is a pure matplotlib solution
#define a color palette index based on column 'B'
df['cind'] = pd.Categorical(df['B']).labels
#how many categories in column 'A'
cats = df['A'].unique()
cats.sort()
#get the seaborn colour palette and convert to array
cp = sns.color_palette()
cpa = np.array(cp)
#draw a subplot for each category in column "A"
fig, axs = plt.subplots(nrows=1, ncols=len(cats), sharey=True)
for i,ax in enumerate(axs):
df_sub = df[df['A'] == cats[i]]
col = cpa[df_sub['cind']]
ax.scatter(df_sub['C'], df_sub['D'], c=col)
eb = ax.errorbar(df_sub['C'], df_sub['D'], yerr=df_sub['E'], fmt=None)
a, (b, c), (d,) = eb.lines
d.set_color(col)
除了labels,还有axis限制就OK了.它为A"列中的每个类别绘制了一个单独的子图,由B"列中的类别着色.(注意随机数据与上面不同)
Other than the labels, and axis limits its OK. Its plotted a separate subplot for each category in column 'A', colored by the category in column 'B'. (Note the random data is different to that above)
如果有人有任何想法,我仍然想要熊猫/seaborn 解决方案吗?
I'd still like a pandas/seaborn solution if anyone has any ideas?
推荐答案
当使用 FacetGrid.map
时,任何引用 data
DataFrame 的东西都必须作为位置传递争论.这将适用于您的情况,因为 yerr
是 plt.errorbar
的第三个位置参数,但为了演示我将使用提示数据集:
When using FacetGrid.map
, anything that refers to the data
DataFrame must be passed as a positional argument. This will work in your case because yerr
is the third positional argument for plt.errorbar
, though to demonstrate I'm going to use the tips dataset:
from scipy import stats
tips_all = sns.load_dataset("tips")
tips_grouped = tips_all.groupby(["smoker", "size"])
tips = tips_grouped.mean()
tips["CI"] = tips_grouped.total_bill.apply(stats.sem) * 1.96
tips.reset_index(inplace=True)
然后我可以使用 FacetGrid
和 errorbar
进行绘图:
I can then plot using FacetGrid
and errorbar
:
g = sns.FacetGrid(tips, col="smoker", size=5)
g.map(plt.errorbar, "size", "total_bill", "CI", marker="o")
但是,请记住,有用于从完整数据集到带有误差条的绘图(使用引导)的 seaborn 绘图函数,因此对于许多应用程序而言,这可能不是必需的.例如,您可以使用 factorplot
:
However, keep in mind that the there are seaborn plotting functions for going from a full dataset to plots with errorbars (using bootstrapping), so for a lot of applications this may not be necessary. For example, you could use factorplot
:
sns.factorplot("size", "total_bill", col="smoker",
data=tips_all, kind="point")
或lmplot
:
sns.lmplot("size", "total_bill", col="smoker",
data=tips_all, fit_reg=False, x_estimator=np.mean)
这篇关于使用 Seaborn FacetGrid 从数据框中绘制错误条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!