Python 如何使用seaborn制作相关热图,但按特定列过滤?
我想在df中的两列之间制作一个相关热图,但要用a3列进行过滤。 我有一个像这样有3列的DF,我想为每个区域制作一张热图,但我找不到制作的方法Python 如何使用seaborn制作相关热图,但按特定列过滤?,python,seaborn,heatmap,Python,Seaborn,Heatmap,我想在df中的两列之间制作一个相关热图,但要用a3列进行过滤。 我有一个像这样有3列的DF,我想为每个区域制作一张热图,但我找不到制作的方法 chldmort adfert region 34.75 7.300000 Africa 122.75 111.699997 Americas 60.25 52.099998 Asia 170.50 124.800003 Europe 168.50 18.600000
chldmort adfert region
34.75 7.300000 Africa
122.75 111.699997 Americas
60.25 52.099998 Asia
170.50 124.800003 Europe
168.50 18.600000 Oceania
我试图在seaborn中实现这一点,但我无法找到一种有效的方法来连续为所有地区实现这一点
tmp=df.loc[:,['chldmort','adfert','region']].dropna()
tmp_africa=tmp[tmp['region']=='Africa']
tmp_americas=tmp[tmp['region']=='Americas']
tmp_asia=tmp[tmp['region']=='Asia']
tmp_europe=tmp[tmp['region']=='Europe']
tmp_oceania=tmp[tmp['region']=='Oceania']
plt.figure(figsize=(20,20))
plt.subplot(5,1,1)
plt.title("chldmort over adfert, grouped by Africa",size=15)
sns.heatmap(tmp_africa.corr(cmap='Reds', annot=True, vmax=.99, vmin=0.60, linewidths=0.9)
plt.subplot(5,1,2)
sns.heatmap(tmp_americas.corr(), cmap='Reds', annot=True, vmax=.99, vmin=0.60, linewidths=0.9)
plt.title("chldmort over adfert, grouped by Americas",size=15)
plt.subplot(5,1,3)
plt.title("chldmort over adfert, grouped by Asia",size=15)
sns.heatmap(tmp_asia.corr(), cmap='Reds', annot=True, vmax=.99, vmin=0.60, linewidths=0.9)
plt.subplot(5,1,4)
plt.title("chldmort over adfert, grouped by Europe",size=15)
sns.heatmap(tmp_europe.corr(), cmap='Reds', annot=True, vmax=.99, vmin=0.60, linewidths=0.9)
plt.subplot(5,1,5)
plt.title("chldmort over adfert, grouped by Oceania",size=15)
sns.heatmap(tmp_oceania.corr(), cmap='Reds', annot=True, vmax=.99, vmin=0.60, linewidths=0.9);
我制作了一些版本来改进绘图。您可以尝试以下方法:
fig = plt.figure(figsize = (30,50))
cont=1
for i in list(set(df.iloc[:,2])): #2 because we are getting the values of the column 2(region)
reg = tmp.loc[tmp['region'] == i] #we get the dataframe filter by region
reg= reg.iloc[:,[0,1]] #we get the columns of chldmort and adfert
ax1 = fig.add_subplot(5, 1, cont) #we are adding a subplot to the general figure
ax1.title.set_text("chldmort over adfert, grouped by "+i) #we set the title of the of ax1 with the current region name
sns.heatmap(reg.corr(), ax=ax1, cmap='Reds', annot=True, vmax=.99, vmin=0.60, linewidths=0.9)
#By doing ax=ax1, we are assigning the subplot ax1 the current heatmap figure
cont=cont+1
您可以查看有关绘制多个热图的更多信息。此外,有关
corr()
的有用信息,您可以单击以下链接:,。tylootmr!:)