如何擦除 matplotlib 图例中的特定标签
How to erase specific labels inside a matplotlib Legend
我正在使用 matplotlib 和 seaborn 绘制散点图。这是我的输出。
正如您在图例右侧看到的那样,有许多颜色相同的标签,我试图擦除除一个以外的所有灰色。这是我的代码:
background = '#eeeeee'
high_c = '#5a83aa'
low_c = '#e09a67'
neutral_c = '#fff8c2'
palette = {'Western Europe':high_c,
'North America and ANZ':'#cccccc',
'Middle East and North Africa':'#cccccc',
'Latin America and Caribbean':'#cccccc',
'Central and Eastern Europe':'#cccccc',
'East Asia':'#cccccc',
'Southeast Asia':'#cccccc',
'Commonwealth of Independent States':'#cccccc',
'Sub-Saharan Africa':low_c,
'South Asia':'#cccccc'
}
fig, ax = plt.subplots(1,1, figsize=(10, 5),dpi=120)
fig.patch.set_facecolor(background) # figure background color
ax.set_facecolor(background)
# plots
sns.scatterplot(data=df21, x='Healthy life expectancy', y='Ladder score',
hue=df21['Regional indicator'],
palette=palette, alpha=0.95,ec='black',
size=df21["Logged GDP per capita"]*1000, legend=True, sizes=(5, 500))
# Axes
ax.set_xlabel("Healthy Life Expectancy",fontfamily='sans serif',loc='left',color='gray')
ax.set_ylabel("Happiness Index Score",fontfamily='sans serif',loc='top',color='gray')
ax.tick_params(axis = 'both', which = 'major', labelsize = 10)
for s in ["top","right","left"]:
ax.spines[s].set_visible(False)
# Annotations
ax.text(45,9.2,'Happiness Score, Life Expectancy, and GDP per Capita',
fontfamily='sans serif',fontweight='normal',fontsize=17,weight='bold',color='#323232')
# Legend
L = ax.legend(frameon=False,loc="upper center", bbox_to_anchor=(1.25, 0.8), ncol= 1)
plt.setp(L.texts, family='sans serif')
L.get_frame().set_facecolor('none')
L.get_texts()[2].set_text('Others')
L.get_texts()[3].set_text('')
L.get_texts()[4].set_text('')
L.get_texts()[5].set_text('')
ax.tick_params(axis='both', which='both',left=False, bottom=False,labelbottom=True)
plt.show()
我想知道如何更改标签上的文本:L.get_texts()[2].set_text('Others'),但找不到如何删除它, 我想要一个只有 'Western Europe', 'Sub-Saharan Africa' 和 'Other'.
的图例
我认为 'handler_map' 或许可以,但我不知道它是如何工作的。
图例自动忽略所有以 '_'
开头的标签。
一个想法是重命名所有灰色区域以 '_'
.
开头
您的代码缺少可重现的数据,但更改可能如下所示:
df21['Regional indicator']
new_name = {month: '_' + month if color == '#cccccc' else month for month, color in palette.items()}
new_name['North America and ANZ'] = 'other'
df21['Regional indicator'] = df21['Regional indicator'].map(new_names)
new_palette = {new_name[month]: color for month, color in palette.items()}
sns.scatterplot(data=df21, x='Healthy life expectancy', y='Ladder score',
hue='Regional indicator',
palette=new_palette, alpha=0.95, ec='black',
size=df21["Logged GDP per capita"] * 1000, legend=True, sizes=(5, 500))
这是一个使用 seaborn 的航班数据集的独立示例。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
flights = sns.load_dataset('flights')
palette = {'Jan': 'crimson', 'Feb': 'limegreen', 'Mar': 'blue', 'Apr': 'gold', 'May': 'purple', 'Jun': '#cccccc',
'Jul': '#cccccc', 'Aug': '#cccccc', 'Sep': '#cccccc', 'Oct': '#cccccc', 'Nov': '#cccccc', 'Dec': '#cccccc'}
new_name = {month: '_' + month if color == '#cccccc' else month for month, color in palette.items()}
new_name['Jun'] = 'other'
flights['month'] = flights['month'].map(new_names)
new_palette = {new_name[month]: color for month, color in palette.items()}
sns.scatterplot(data=flights, x='year', y='passengers', hue='month', palette=new_palette)
plt.show()
我正在使用 matplotlib 和 seaborn 绘制散点图。这是我的输出。
正如您在图例右侧看到的那样,有许多颜色相同的标签,我试图擦除除一个以外的所有灰色。这是我的代码:
background = '#eeeeee'
high_c = '#5a83aa'
low_c = '#e09a67'
neutral_c = '#fff8c2'
palette = {'Western Europe':high_c,
'North America and ANZ':'#cccccc',
'Middle East and North Africa':'#cccccc',
'Latin America and Caribbean':'#cccccc',
'Central and Eastern Europe':'#cccccc',
'East Asia':'#cccccc',
'Southeast Asia':'#cccccc',
'Commonwealth of Independent States':'#cccccc',
'Sub-Saharan Africa':low_c,
'South Asia':'#cccccc'
}
fig, ax = plt.subplots(1,1, figsize=(10, 5),dpi=120)
fig.patch.set_facecolor(background) # figure background color
ax.set_facecolor(background)
# plots
sns.scatterplot(data=df21, x='Healthy life expectancy', y='Ladder score',
hue=df21['Regional indicator'],
palette=palette, alpha=0.95,ec='black',
size=df21["Logged GDP per capita"]*1000, legend=True, sizes=(5, 500))
# Axes
ax.set_xlabel("Healthy Life Expectancy",fontfamily='sans serif',loc='left',color='gray')
ax.set_ylabel("Happiness Index Score",fontfamily='sans serif',loc='top',color='gray')
ax.tick_params(axis = 'both', which = 'major', labelsize = 10)
for s in ["top","right","left"]:
ax.spines[s].set_visible(False)
# Annotations
ax.text(45,9.2,'Happiness Score, Life Expectancy, and GDP per Capita',
fontfamily='sans serif',fontweight='normal',fontsize=17,weight='bold',color='#323232')
# Legend
L = ax.legend(frameon=False,loc="upper center", bbox_to_anchor=(1.25, 0.8), ncol= 1)
plt.setp(L.texts, family='sans serif')
L.get_frame().set_facecolor('none')
L.get_texts()[2].set_text('Others')
L.get_texts()[3].set_text('')
L.get_texts()[4].set_text('')
L.get_texts()[5].set_text('')
ax.tick_params(axis='both', which='both',left=False, bottom=False,labelbottom=True)
plt.show()
我想知道如何更改标签上的文本:L.get_texts()[2].set_text('Others'),但找不到如何删除它, 我想要一个只有 'Western Europe', 'Sub-Saharan Africa' 和 'Other'.
的图例我认为 'handler_map' 或许可以,但我不知道它是如何工作的。
图例自动忽略所有以 '_'
开头的标签。
一个想法是重命名所有灰色区域以 '_'
.
您的代码缺少可重现的数据,但更改可能如下所示:
df21['Regional indicator']
new_name = {month: '_' + month if color == '#cccccc' else month for month, color in palette.items()}
new_name['North America and ANZ'] = 'other'
df21['Regional indicator'] = df21['Regional indicator'].map(new_names)
new_palette = {new_name[month]: color for month, color in palette.items()}
sns.scatterplot(data=df21, x='Healthy life expectancy', y='Ladder score',
hue='Regional indicator',
palette=new_palette, alpha=0.95, ec='black',
size=df21["Logged GDP per capita"] * 1000, legend=True, sizes=(5, 500))
这是一个使用 seaborn 的航班数据集的独立示例。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
flights = sns.load_dataset('flights')
palette = {'Jan': 'crimson', 'Feb': 'limegreen', 'Mar': 'blue', 'Apr': 'gold', 'May': 'purple', 'Jun': '#cccccc',
'Jul': '#cccccc', 'Aug': '#cccccc', 'Sep': '#cccccc', 'Oct': '#cccccc', 'Nov': '#cccccc', 'Dec': '#cccccc'}
new_name = {month: '_' + month if color == '#cccccc' else month for month, color in palette.items()}
new_name['Jun'] = 'other'
flights['month'] = flights['month'].map(new_names)
new_palette = {new_name[month]: color for month, color in palette.items()}
sns.scatterplot(data=flights, x='year', y='passengers', hue='month', palette=new_palette)
plt.show()