我正在努力将Seaborn facetgrid与数据放在一起,这些数据会留下一些网格。此外,我用一些统计数据来注释每个方面,但是我不确定如何跳过"跳过"空面,使注释落在正确的方面。
g.axes.flat
长度为9(9个方面有数据);但是,当我在g.axes.flat
中的每个元素上放置注释时,它不会被放置在我期望的位置。
g = sns.FacetGrid(mapping, col=options.facetCol, row=options.facetRow, col_order=sorted(cols), hue=options.group, sharex=False)
g = g.map(sns.distplot, options.axis)
# label each facet with stats
grouped = mapping.groupby([options.facetRow, options.facetCol])
for ax, (name, df) in zip(g.axes.flat, grouped):
df2 = df.groupby(options.group) # group by each thing that has its own color and run stats on it
for i, (group, data) in enumerate(df2):
x = data[options.axis]
# calculate stats and create label
n = len(x)
mean = np.mean(x)
std = np.std(x)
label = r"%s: n=%s, $\mu$=%.2f $\sigma$=%.2f" %(group, n, mean, std)
ax.annotate(label, xy=(0.05,0.9-(i*0.05)), xycoords='axes fraction', ha='left', size=8)
我已经创建了一个注释功能,并且我将其传递给map()
[推荐];但我不确定如何将标签名称传递给函数以及如何获取注释(每个方面有两个)在y方向上移位。还有其他建议吗?
g = g.map(stats, options.axis)
def stats(x, **kwargs):
ax = sns.distplot(x, **kwargs)
# calculate stats and create label
n = len(x)
mean = np.mean(x)
std = np.std(x)
label = r"%s: n=%s, $\mu$=%.2f $\sigma$=%.2f" %('moo', n, mean, std) # temporary label, need to pass it through function
i = 1 # temporary, needs to increment to shift annotations so they aren't on top of each other
# create annotation
ax.annotate(label, xy=(0.05,0.9-(i*0.05)), xycoords='axes fraction', ha='left', size=8)
答案 0 :(得分:3)
最终解决方案是:
g = sns.FacetGrid(mapping, col=options.facetCol, row=options.facetRow, col_order=sorted(cols), hue=options.group, sharex=False)
g.map(sns.distplot, options.axis)
g.map(stats, options.axis)
# custom function that allows us to create a distplot and add offset annotations to each facet that is not empty
def stats(x, label, **kwargs):
# get a reference to the currently active axes
ax = plt.gca()
# calculate stats and create label
n = len(x)
mean = np.mean(x)
std = np.std(x)
label = r"%s: n=%s, $\mu$=%.2f $\sigma$=%.2f" %(label, n, mean, std)
# create annotation
y = 0.9 - len(ax.texts) * 0.05
ax.annotate(label, xy=(0.05,y), xycoords='axes fraction', ha='left', size=8)