Seaborn stripplot和错误栏

时间:2016-07-06 09:31:02

标签: python matplotlib seaborn subplot

我有一个包含分类数据的pandas数据框,如下所示:

      cat     DM3_r  DM3_r_err
133   stuff  9.908949   0.442363
1347  foo  1.156828   0.130174
132   bar  0.818709   0.593341
1350  stack  0.798348   0.089866
977   over  0.724274   0.462868
1054  flow  0.546665   0.538208
1228  run  0.425070   0.571659
1009  run  0.316554   0.259385
1109  yadG  0.304657   0.401482

我正在使用seaborn的stripplot来显示数据:

seaborn.stripplot(df.DM3_r, df.cat, size=7, orient="h", 
              palette="Reds_r", edgecolor="gray", ax=ax.flat[i], linewidth=.5)

在这种情况下针对"cat"的不同组。这很好用。但是,我想添加错误"DM3_r_err"

我已经从errorbar尝试matplotlib在顶部添加错误栏图,但我无法提取seaborn图表中点的位置。这可能是由于我使用的是子图。​​

是否有使用seaborn的直接方式?

这是stripplot的样子(左),右侧是我的目标: enter image description here

1 个答案:

答案 0 :(得分:2)

可能有更智能的方式从Pandas.DataFrame中选择数据,但这样的方法有效:

import pandas as pd
import matplotlib.pylab as pl
import seaborn
import numpy as np

pl.close('all')

data = [['hsdM', 3.908949, 1.442363],
        ['lolD', 1.156828, 0.456434],
        ['lolD', 3.156828, 0.230174],
        ['acrB', 0.546665, 0.538208],
        ['msbA', 0.425070, 0.571659],
        ['msbA', 2.425070, 1.571659],
        ['emrA', 0.316554, 1.259385],
        ['yadG', 0.304657, 0.401482]]

df = pd.DataFrame(data, columns=['gene','DM3_r','DM3_r_err'])

pl.figure()
ax = pl.subplot(111)

# Everywhere below you would have to replace `ax` with your `ax.flat[i]`
sp = seaborn.stripplot(df.DM3_r, df.gene, size=7, orient="h", 
                     palette="Reds_r", edgecolor="gray", ax=ax, linewidth=.5)

for y,ylabel in zip(ax.get_yticks(), ax.get_yticklabels()):
    f = df['gene'] == ylabel.get_text() 
    ax.errorbar(df.DM3_r[f].values, np.ones_like(df.DM3_r[f].values)*y, xerr=df.DM3_r_err[f].values, ls='none')

enter image description here