簡體   English   中英

Seaborn 和 matplotlib 控制子圖中的圖例

[英]Seaborn and matplotlib control legend in subplots

我一直在玩 plt.legend() 和 ax.legend() 以及來自 seaborn 本身的傳奇,我想我錯過了一些東西。

我的第一個問題是,有人可以向我解釋這些是如何組合在一起的,它們是如何工作的,如果我有子情節,什么比什么更好? 意思是我可以設置一個通用定義(例如,在這個 loc 的所有子圖中都有這個圖例),然后為特定的子圖覆蓋這個定義(例如通過 ax.legend())?

我的第二個問題是實用的,並顯示了我的問題。 讓我們用 seaborn Smokers 數據集來說明:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

# define sizes for labels, ticks, text, ...
# as defined here https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot
SMALL_SIZE = 10
MEDIUM_SIZE = 14
BIGGER_SIZE = 18

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=MEDIUM_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=MEDIUM_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title


# create figure
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(16,12))
ylim = (0,1)

sns.boxplot(x= 'day', y= 'tip', hue="sex",
                  data=tips, palette="Set2", ax=ax1)
sns.swarmplot(x= 'day', y= 'tip', hue="sex",
                  data=tips, palette="Set2", ax=ax2)
ax2.legend(loc='upper right')

sns.boxplot(x= 'day', y= 'total_bill', hue="sex",
                  data=tips, palette="Set2", ax=ax3)
sns.swarmplot(x= 'day', y= 'total_bill', hue="sex",
                  data=tips, palette="Set2", ax=ax4)


plt.suptitle('Smokers')
plt.legend(loc='upper right')

plt.savefig('test.png', dpi = 150)

情節示例。

如果我只使用 seaborn,我會得到一個圖例,如 Subplot 1 和 3 中的圖例——它具有“色調”標簽並遵循定義的字體大小。 但是,我無法控制它的位置(它有一些默認值,請參閱 1 和 3 之間的區別)。 如果我在 Subplot 2 中使用 ax.legend(),那么我可以修改特定的 subplot,但我失去了 seaborn 'hue' 功能(注意“sex”消失了)並且它不遵循我的字體定義。 如果我使用 plt.legend(),它只會影響它之前的子圖(在這種情況下為子圖 4)。 我怎樣才能把這一切統一起來? 例如。 對所有子圖有一個定義或如何控制 seaborn 默認? 為了明確目標,如何在子圖 1 中創建一個圖例,其中標簽自動來自數據(但我可以更改它們),並且所有子圖的位置、字體大小...設置相同(例如右上角,字體大小為 10,...)?

謝謝你的幫助和解釋。

Seaborn Legends 總是使用關鍵字loc=best調用。 這是在源代碼中硬編碼的。 您可以更改源代碼,例如在這一行中並替換為ax.legend() 然后在您的代碼中設置 rc 參數,例如

plt.rc('legend', loc="upper right")

將給出所需的輸出。

唯一的其他選擇是手動創建圖例,就像您在第二種情況下所做的那樣,

ax2.legend(loc="upper right", title="sex", title_fontsize="x-large")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM