[英]Seaborn Violin Plot - Apply hue and split options to different features
[英]Creating a violin plot with seaborn without x and y values but with hue
我正在嘗試使用 seaborn 創建小提琴 plot。
我的 df 看起來像這樣:
drought
Out[65]:
Dataset TGLO TAM TAFR TAA Type
0 ACCESS1-0 0.181017 0.068988 0.166761 0.069303 AMIP
1 ACCESS1-3 0.109676 -0.001961 -0.008700 0.373162 AMIP
2 BNU-ESM 0.277070 0.272242 0.266324 -0.077017 AMIP
3 CCSM4 0.385075 0.258976 0.304438 0.211241 AMIP
...
21 CMAP 0.087274 -0.062214 -0.079958 0.372267 OBS
22 ERA 0.179999 -0.010484 0.134584 0.204052 OBS
23 GPCC 0.173947 -0.020719 0.021819 0.370157 OBS
24 GPCP 0.151394 0.036450 -0.021462 0.336876 OBS
25 UEA 0.223828 -0.018237 0.088486 0.398062 OBS
26 UofD 0.190969 0.094744 0.036374 0.310938 OBS
我想要一個基於類型的分裂小提琴 plot 這是我正在使用的代碼
sns.violinplot(data=drought, hue='Type', split=True)
這是錯誤:
Cannot use `hue` without `x` or `y`
我沒有 x 或 y 值,因為我想要的是將列作為 x,將行中的值作為 y。
謝謝你的幫助!
您想忽略“數據集”列並為其他 4 列拆分小提琴嗎? 在這種情況下,您需要將這 4 列轉換為“長格式” (通過 pandas 的melt()
)。
這是一個例子:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
drought = pd.DataFrame({'Dataset': ["".join(np.random.choice([*'VWXYZ'], 5)) for _ in range(40)],
'TGLO': np.random.randn(40),
'TAM': np.random.randn(40),
'TAFR': np.random.randn(40),
'TAA': np.random.randn(40),
'Type': np.repeat(['AMIP', 'OBS'], 20)})
drought_long = drought.melt(id_vars=['Dataset', 'Type'], value_vars=['TGLO', 'TAM', 'TAFR', 'TAA'])
sns.set_style('white')
ax = sns.violinplot(data=drought_long, x='variable', y='value', hue='Type', split=True, palette='flare')
ax.legend()
sns.despine()
plt.tight_layout()
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.