我想从Seaborn FacetGrid上的pandas数据框的列中绘制错误条
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
此代码适用于固定大小的误差线:
g = sns.FacetGrid(df, col="A", hue="B", size =5)
g.map(plt.errorbar, "C", "D",yerr=0.5, fmt='o');
但是我不能用数据框中的值来实现它
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解决方案
#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)
除标签外,轴限制其正常。它为“a”列中的每个类别绘制了一个单独的子批次,由“B”列中的类别着色。(注意随机数据与上述不同)
如果有人有什么想法的话,我还是想要一个熊猫/海生的解决方案?
使用
FacetGrid.map
时,任何引用data
数据帧的内容都必须作为位置参数传递。这在您的情况下是可行的,因为yerr
是plt.errorbar
的第三个位置参数,不过为了演示我将使用tips数据集:然后我可以使用
FacetGrid
和errorbar
绘制:但是,请记住,有seaborn绘图函数用于从完整数据集到带有错误条的绘图(使用引导),因此对于许多应用程序,这可能不是必需的。例如,可以使用
factorplot
:或
lmplot
:你没有显示
df['E']
实际上是什么,如果它是与df['C']
和df['D']
长度相同的列表。关键字参数(kwarg)接受一个值,该值将应用于数据帧中键C和D的列表中的每个元素,或者需要一个与这些列表长度相同的值列表。
所以,C、D和E都必须与相同长度的列表相关联,或者C和D必须是相同长度的列表,并且E必须与单个
float
或int
相关联。如果单个float
或int
在列表中,则必须提取它,如df['E'][0]
。示例
matplotlib
代码与yerr
: http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html描述
yerr
的条形图API文档: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar相关问题 更多 >
编程相关推荐