如何使用 seaborn 制作相关热图但按特定列过滤?

How to make a correlation heatmap with seaborn but filtering by a specific column?

我想在 df 中的 2 列之间制作相关热图,但按 a3 列过滤。 我有一个像这样的 DF,有 3 列,我想为每个区域制作 1 个热图,但我找不到制作它的方法。

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

您可以查看有关绘制多个热图的更多信息here. And, for helpful info about corr(), you can click these links: heatmap-correlations, corr()