2017-01-03 131 views
3

我想繪製3個水平條形圖,標籤爲y軸,數據爲x軸,我希望每個圖都是不同的顏色,並有一定類型的註釋,如依賴於由列中的數據表示的signficiance,例如星號:如何使用seaborn pairgird和seaborn barplot爲每個圖添加顏色和星號

dat = pd.DataFrame({ 
    'Labels':['v1','v2','c1','c2'], 
    'Ave': [.2, .3, .5, .9], 
    'SD': [0.02, 0.1, 0.04, 0.06], 
    'Tot': [3, 4, 6, 8], 
    'Sig': [0.05, 0.001, 0.0001, 0.05] 
}) 

sns.set_style('white') 

g = sns.PairGrid(dat, x_vars=['Ave', 'SD', 'Tot'], y_vars=['Labels']) 
g.map(sns.barplot) 

會讓我這樣的事情:

enter image description here

我如何獲得每個小區的「Ave」「SD」和「ToT 「是他們自己的顏色?以及如何添加註釋來表示「Sig」列給出的重要性?

回答

0

還沒有想出如何得到這個與seaborn做,但這個matplotlib將工作

import pandas as pd 

dat = pd.DataFrame({ 
    'Labels':['v1','v2','c1','c2'], 
    'Ave': [.2, .3, .5, .9], 
    'SD': [0.02, 0.1, 0.04, 0.06], 
    'Tot': [3, 4, 6, 8], 
    'Sig':[0.05, 0.005, 0.0001, 0.05], 
    'Sig_mask': [1,2,3,1], 
}) 

import matplotlib.pyplot as plt 
fig = plt.figure() 

# multiple plots 
ax1 = fig.add_subplot(131) 

# horizontal bar plot and set color 
ax1.barh(dat.index.values, dat['SD'], color='r', align='center') 

# SET SPINES VISIBLE 
ax1.spines['right'].set_visible(False) 
ax1.spines['top'].set_visible(False) 

# SET X, Y LABELS 
ax1.set(yticks=dat.index.values, yticklabels=dat.Labels.values) 
ax1.set(xlabel='SD') 

# ADD SIG NOTATION 
for idx, val in enumerate(dat.SD.values): 
    ax1.text(x=val+.003, y=idx, s='*'*dat.Sig_mask[idx], va='center') 

# ADD SECOND PLOT 
ax2 = fig.add_subplot(132) 
# everything else much in the same manner, change color and data column 


# ADD THIRD PLOT 
ax3 = fig.add_subplot(133) 
# same as above 
1

你可以通過你的數據整形爲長(整齊)格式的親近和使用factorplot

重塑:

dat = (
    pandas.DataFrame({ 
     'Labels':['v1','v2','c1','c2'], 
     'Ave': [.2, .3, .5, .9], 
     'SD': [0.02, 0.1, 0.04, 0.06], 
     'Tot': [3, 4, 6, 8], 
     'Sig': [0.05, 0.001, 0.0001, 0.05] 
    }).set_index('Labels') 
    .unstack() 
    .reset_index() 
    .rename(columns={ 
     'level_0': 'stat', 
     0: 'result' 
    }) 
) 

print(dat.head(8)) 

    stat Labels result 
0 Ave  v1 0.20 
1 Ave  v2 0.30 
2 Ave  c1 0.50 
3 Ave  c2 0.90 
4 SD  v1 0.02 
5 SD  v2 0.10 
6 SD  c1 0.04 
7 SD  c2 0.06 

而且factorplot:

seaborn.factorplot('result', 'Labels', data=dat, 
        kind='bar', sharex=False, 
        hue='stat', hue_order=stats, 
        col='stat', col_order=stats) 

enter image description here

的問題是條偏移因爲使用hue告訴seaborn在每個Y,以騰出空間爲不同類別-位置。

在下一個版本中,您將能夠說出dodge=False以避免這種偏移。