[英]Seaborn (time series) boxplot using hue and different scale axes
我有一個數據框,每個日期有多個值(日期時間字段)。 使用列Group將此值分類為 U(用戶)和 S(會話)。 Seaborn 用於可視化每個日期的兩個箱線圖,其中色調設置為Group 。
當考慮到 U(用戶)對應的值比 S(會話)對應的值大得多時,問題就出現了,使得 S 數據難以辨認。 因此,我需要想出一個解決方案,使我能夠以可理解的方式在同一圖中繪制兩個系列(U 和 S)。
我想知道是否可以為每個色調設置獨立的 Y 軸(具有不同的比例),以便顯示兩個 Y 軸(就像使用twinx
但不失去色調可視化功能時一樣)。
歡迎任何其他選擇 =)
S 箱線圖時間序列箱線圖:
使用色調的組合箱線圖時間序列。 顯然,由於 Y 軸的刻度,無法看到有關 S 組的任何信息:
數據框的列:
| 日(日期時間)| n_data(數字)| 組(S 或 U)|
生成組合箱線圖的代碼行:
seaborn.boxplot(ax=ax,x='Day', y='n_data', hue='Group', data=df,
palette='PRGn', showfliers=False)
設法通過使用 twinx 找到了解決方案:
fig,ax= plt.subplots(figsize=(50,10))
tmpU = groups.copy()
tmpU.loc[tmp['Group']!='U','n_data'] = np.nan
tmpS = grupos.copy()
tmpS.loc[tmp['Group']!='S','n_data'] = np.nan
ax=seaborn.boxplot(ax=ax,x='Day', y = 'n_data', hue='Group', data=tmpU, palette = 'PRGn', showfliers=False)
ax2 = ax.twinx()
seaborn.boxplot(ax=ax2,x='Day', y = 'n_data', hue='Group', data=tmpS, palette = 'PRGn', showfliers=False)
handles,labels = ax.get_legend_handles_labels()
l= plt.legend(handles[0:2],labels[0:2],loc=1)
plt.setp(ax.get_xticklabels(),rotation=30,horizontalalignment='right')
for label in ax.get_xticklabels()[::2]:
label.set_visible(False)
plt.show()
plt.close('all')
上面的代碼生成下圖:
在這種情況下,結果太密集而無法發布。 因此,我會采用基於子圖的可視化,正如 Parfait 在他/她的回答中所說的那樣。
這對我來說不是一個明顯的解決方案,所以我要感謝 Parfait 的回答。
考慮在同一圖上構建單獨的圖,y 軸范圍針對子集數據量身定制。 下面演示了隨機數據的可重復性(對於這篇文章的讀者)。
數據(U 值高於 S 值)
import pandas as pd
import numpy as np
import seaborn
import matplotlib.pyplot as plt
np.random.seed(2018)
u_df = pd.DataFrame({'Day': pd.date_range('2016-10-01', periods=10)\
.append(pd.date_range('2016-10-01', periods=10)),
'n_data': np.random.uniform(0,800,20),
'Group': 'U'})
s_df = pd.DataFrame({'Day': pd.date_range('2016-10-01', periods=10)\
.append(pd.date_range('2016-10-01', periods=10)),
'n_data': np.random.uniform(0,200,20),
'Group': 'S'})
df = pd.concat([u_df, s_df], ignore_index=True)
df['Day'] = df['Day'].astype('str')
陰謀
fig = plt.figure(figsize=(10,5))
for i,g in enumerate(df.groupby('Group')):
plt.title('N_data of {}'.format(g[0]))
plt.subplot(2, 1, i+1)
seaborn.boxplot(x="Day", y="n_data", data=g[1], palette="PRGn", showfliers=False)
plt.tight_layout()
plt.show()
plt.clf()
plt.close('all')
要保留原始色調和分組,請將所有非組n_data渲染為np.nan
:
fig = plt.figure(figsize=(10,5))
for i,g in enumerate(df.Group.unique()):
plt.subplot(2, 1, i+1)
tmp = df.copy()
tmp.loc[tmp['Group']!=g, 'n_data'] = np.nan
seaborn.boxplot(x="Day", y="n_data", hue="Group", data=tmp,
palette="PRGn", showfliers=False)
plt.tight_layout()
plt.show()
plt.clf()
plt.close('all')
所以一個選項做了分組箱線圖有兩個獨立的軸是用hue_order= ['value, np.nan]
在論證中sns.boxplot
:
fig = plt.figure(figsize=(14,8)) ax = sns.boxplot(x="lon_bucketed", y="value", data=m, hue='name', hue_order=['co2',np.nan], width=0.75,showmeans=True,meanprops={"marker":"s","markerfacecolor":"black", "markeredgecolor":"black"},linewidth=0.5 ,palette = customPalette) ax2 = ax.twinx() ax2 = sns.boxplot(ax=ax2,x="lon_bucketed", y="value", data=m, hue='name', hue_order=[np.nan,'g_xco2'], width=0.75,showmeans=True,meanprops={"marker":"s","markerfacecolor":"black", "markeredgecolor":"black"},linewidth=0.5, palette = customPalette) ax1.grid(alpha=0.5, which = 'major') plt.tight_layout() ax.legend_.remove() GW = mpatches.Patch(color='seagreen', label='$CO_2$') WW = mpatches.Patch(color='mediumaquamarine', label='$XCO_2$') ax, ax2.legend(handles=[GW,WW], loc='upper right',prop={'size': 14}, fontsize=12) ax.set_title("$XCO_2$ vs. $CO_2$",fontsize=18) ax.set_xlabel('Longitude [\°]',fontsize=14) ax.set_ylabel('$CO_2$ [ppm]',fontsize=14) ax2.set_ylabel('$XCO_2$ [ppm]',fontsize=14) ax.tick_params(labelsize=14)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.