Sos*_*hty 2 python matlab matplotlib pandas seaborn
我有这三个子图,我需要在顶部匹配下方的两个子图的图例中设置大陆的颜色,即欧洲 = 蓝色,亚洲 = 红色,等等。有没有办法做到这一点?我正在使用 Python、seaborn 和 Matplotlib。这是我的代码和结果图:
fig = plt.figure(figsize=(20,10))
ax1 = plt.subplot(2, 1, 1)
diseases.plot(kind="barh", ax = ax1, width = 0.9, cmap = 'Set1_r')
ax1.set_xticks(np.arange(0,251,25))
ax1.set_ylabel('Countries', fontsize = 15)
ax1.legend(fontsize = 12)
ax2 = plt.subplot(2, 2, 3)
sns.barplot(x = smok_fem.female_smokers, y = smok_fem.index , hue='continent', data = smok_fem, ax = ax2,
dodge = False, palette = 'tab10')
ax2.set_xlabel('Female Smokers', fontsize = 14)
ax2.set_ylabel('Countries', fontsize = 14)
ax2.legend(fontsize = 14, markerscale = 2, facecolor = 'w')
ax3 = plt.subplot(2, 2, 4)
sns.barplot(x = smok_mal.male_smokers, y = smok_mal.index , hue='continent', data = smok_mal, ax = ax3, dodge = False,
palette = 'tab10')
ax3.invert_yaxis()
ax3.invert_xaxis()
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position("right")
ax3.set_xlabel('Male Smokers', fontsize = 14)
ax3.set_ylabel('Countries', fontsize = 14)
ax3.legend(fontsize = 14, facecolor = 'w')
plt.show()
Run Code Online (Sandbox Code Playgroud)
提前致谢!
Seaborn 还接受字典作为调色板。字典会将每个色调值(在本例中为大陆)映射到其颜色。
这是使用测试数据的示例。请注意,您还可以编写字典以{'Europe': 'blue', 'Asia': 'red', ....}更好地控制颜色。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
continents = ['Europe', 'Asia', 'Africa', 'North America', 'South America', 'Oceania']
df = pd.DataFrame({'country': [*'ABCDEFGHIJKLMNOPQRSTUVWXYZ'],
'continent': np.random.choice(continents, 26),
'female_smokers': np.random.uniform(20, 60, 26),
'male_smokers': np.random.uniform(20, 60, 26),
})
df = df.set_index('country')
smok_fem = df.sort_values('female_smokers')
smok_mal = df.sort_values('male_smokers')
palette_colors = sns.color_palette('tab10')
palette_dict = {continent: color for continent, color in zip(continents, palette_colors)}
fig = plt.figure(figsize=(20, 10))
ax2 = plt.subplot(1, 2, 1)
sns.barplot(x=smok_fem.female_smokers, y=smok_fem.index, hue='continent', data=smok_fem, ax=ax2,
dodge=False, palette=palette_dict)
ax2.set_xlabel('Female Smokers', fontsize=14)
ax2.set_ylabel('Countries', fontsize=14)
ax2.legend(fontsize=14, markerscale=2, facecolor='w')
ax3 = plt.subplot(1, 2, 2)
sns.barplot(x=smok_mal.male_smokers, y=smok_mal.index, hue='continent', data=smok_mal, ax=ax3, dodge=False,
palette=palette_dict)
ax3.invert_yaxis()
ax3.invert_xaxis()
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position("right")
ax3.set_xlabel('Male Smokers', fontsize=14)
ax3.set_ylabel('Countries', fontsize=14)
ax3.legend(fontsize=14, facecolor='w')
plt.show()
Run Code Online (Sandbox Code Playgroud)
请注意,各大洲的显示顺序与数据框中的显示顺序相同。未出现在数据框中的大陆将不会出现在图例中。您还可以通过修复“色调顺序” hue_order=continents。在这种情况下,所有大陆都将出现在图例中,无论它们是否出现在数据框中。