![](/img/trans.png)
[英]How to edit a seaborn legend title and labels for figure-level functions
[英]Edit legend title and labels of Seaborn scatterplot and countplot
我在 titanic 數據集上使用 seaborn 散點圖和計數圖。
這是我繪制散點圖的代碼。 我還嘗試編輯圖例標簽。
ax = seaborn.countplot(x='class', hue='who', data=titanic)
legend_handles, _ = ax.get_legend_handles_labels()
plt.show();
要編輯圖例標簽,我這樣做了。 在這種情況下,不再有圖例標題。 如何將此標題從“who”重命名為“who1”?
ax = seaborn.countplot(x='class', hue='who', data=titanic)
legend_handles, _= ax.get_legend_handles_labels()
ax.legend(legend_handles, ['man1','woman1','child1'], bbox_to_anchor=(1,1))
plt.show()
我用同樣的方法編輯散點圖上的圖例標簽,這里的結果不同。 它使用“死亡”作為圖例標題,並使用“幸存”作為第一個圖例標簽。
ax = seaborn.scatterplot(x='age', y='fare', data=titanic, hue = 'survived')
legend_handles, _= ax.get_legend_handles_labels()
ax.legend(legend_handles, ['dead', 'survived'],bbox_to_anchor=(1.26,1))
plt.show()
是否有刪除和添加圖例標題的參數?
我在兩個不同的圖表上使用了相同的代碼,圖例的結果是不同的。 這是為什么?
嘗試使用
ax.legend(legend_labels, ['man1','woman1','child1'],
bbox_to_anchor=(1,1),
title='whatever title you want to use')
對於 seaborn v0.11.2 或更高版本,使用move_legend()
函數。
從常見問題解答頁面:
對於 seaborn v0.11.2 或更高版本,使用 move_legend() 函數。
在舊版本中,一種常見的模式是在繪圖后調用 ax.legend(loc=...) 。 雖然這似乎移動了圖例,但它實際上用一個新的圖例替換了圖例,使用了恰好附加到軸上的任何帶標簽的藝術家。 這並不適用於各種繪圖類型。 而且它不會傳播用於格式化多變量圖例的圖例標題或定位調整。
move_legend()函數其實比它的名字更強大,它還可以用來在出圖后修改其他圖例參數(字體大小、句柄長度等)。
您可以通過hue_order=['man', 'woman', 'child']
強制圖例的順序。 默認情況下,順序要么是它們在數據框中出現的順序(當值只是字符串時),要么是pd.Categorical
強加的順序。
最可靠的方法是重命名列值,例如
titanic["who"] = titanic["who"].map({'man': 'Man1', 'woman': 'Woman1', 'child': 'Child1'})
如果列的條目存在0,1,...
范圍內的數字,則可以使用pd.Categorical.from_codes(...)
。 這也強制執行命令。
有許多選項可以指定要使用的顏色(通過palette=
)。 要將特定顏色分配給特定色調值,調色板可以是字典,例如
palette = {'Man1': 'cornflowerblue', 'Woman1': 'fuchsia', 'Child1': 'limegreen'}
sns.move_legend(ax, title=..., loc='best')
設置一個新標題。 將標題設置為空字符串會將其刪除(這在條目不言自明時很有用)。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
titanic = sns.load_dataset('titanic')
# titanic['survived'] = titanic['survived'].map({0:'Dead', 1:'Survived'})
titanic['survived'] = pd.Categorical.from_codes(titanic['survived'], ['Dead', 'Survived'])
palette = {'Dead': 'navy', 'Survived': 'turquoise'}
ax = sns.scatterplot(data=titanic, x='age', y='fare', hue='survived', palette=palette)
sns.move_legend(ax, title='', loc='best') # remove the title
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.