我有一個包含 8 列和幾行的資料集。這些列包含在 2 個不同條件下對不同變數(總共 6 個)的測量值,每列包含 4 個包含特定條件重復測量值的列。
使用 Searborn,我想生成一個條形圖,顯示每 4 列的平均值和標準偏差,按索引鍵(即測量變數)分組。資料幀結構如下:
np.random.seed(10)
df = pd.DataFrame({
'S1_1':np.random.randn(6),
'S1_2':np.random.randn(6),
'S1_3':np.random.randn(6),
'S1_4':np.random.randn(6),
'S2_1':np.random.randn(6),
'S2_2':np.random.randn(6),
'S2_3':np.random.randn(6),
'S2_4':np.random.randn(6),
},index= ['var1','var2','var3','var4','var5','var6'])
我如何傳遞給我只想要 2 個小節的 seaborn,前 4 列 1 個,第二個 1 個。每個條形顯示跨 4 列的平均值(和標準偏差或其他一些分散度量)。
我正在考慮使用多索引,添加第二個列級別將列分組為 2 個條件,
df.columns = pd.MultiIndex.from_arrays([['Condition 1'] * 4 ['Condition 2'] * 4,df.columns])
但我不知道我應該傳遞給 Seaborn 什么來生成我想要的情節。
如果有人能指出我正確的方向,那將是一個很大的幫助!
uj5u.com熱心網友回復:
根據評論更新
- 繪圖就是為繪圖 API 重塑資料框
# still create the groups
l = df.columns
n = 4
groups = [l[i:i n] for i in range(0, len(l), n)]
num_gps = len(groups)
# stack each group and add an id column
data_list = list()
for group in groups:
id_ = group[0][1]
data = df[group].copy().T
data['id_'] = id_
data_list.append(data)
df2 = pd.concat(data_list, axis=0).reset_index()
df2.rename({'index': 'sample'}, axis=1, inplace=True)
# melt df2 into a long form
dfm = df2.melt(id_vars=['sample', 'id_'])
# plot
p = sns.catplot(kind='bar', data=dfm, x='variable', y='value', hue='id_', ci='sd', aspect=3)
df2.head()
sample YAL001C YAL002W YAL004W YAL005C YAL007C YAL008W YAL011W YAL012W YAL013W YAL014C id_
0 S2_1 -13.062716 -8.084685 2.360795 -0.740357 3.086768 -0.117259 -5.678183 2.527573 -17.326287 -1.319402 2
1 S2_2 -5.431474 -12.676807 0.070569 -4.214761 -4.318011 -4.489010 -10.268632 0.691448 -24.189106 -2.343884 2
2 S2_3 -9.365509 -12.281169 0.497772 -3.228236 0.212941 -2.287206 -10.250004 1.111842 -27.811564 -4.329987 2
3 S2_4 -7.582111 -15.587219 -1.286167 -4.531494 -3.090265 -4.718281 -8.933496 2.079757 -21.580854 -2.834441 2
4 S3_1 -12.618254 -20.010779 -2.530541 -3.203072 -2.436503 -2.922565 -15.972632 3.551605 -35.618485 -4.925495 3
dfm.head()
sample id_ variable value
0 S2_1 2 YAL001C -13.062716
1 S2_2 2 YAL001C -5.431474
2 S2_3 2 YAL001C -9.365509
3 S2_4 2 YAL001C -7.582111
4 S3_1 3 YAL001C -12.618254
繪圖結果

kind='box'
- 箱線圖可能更好地傳達分布
p = sns.catplot(kind='box', data=dfm, y='variable', x='value', hue='id_', height=12)

原答案
- 使用串列理解將列分成 4 組
- This uses the original, more comprehensive data that was posted. It can be found in
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/339360.html標籤:Python 熊猫 matplotlib 海生 条形图
- This uses the original, more comprehensive data that was posted. It can be found in
