KDE Plot Part 2
Solution
HIC = df[df["Income Level"]=="HIC"]
MIC = df[df["Income Level"]=="MIC"]
LIC = df[df["Income Level"]=="LIC"]
To create the three different plots we call kdeplot() three times with our different data.
sns.kdeplot(HIC["Population"],HIC["GDP per Capita"],shade=True,shade_lowest=False)
sns.kdeplot(MIC["Population"],MIC["GDP per Capita"],shade=True,shade_lowest=False)
sns.kdeplot(LIC["Population"],LIC["GDP per Capita"],shade=True,shade_lowest=False)
plt.show()
It would be helpful to use different colors to identify these plots. Using the cmap argument, we can tell seaborn to find a perset color map to use.
sns.kdeplot(HIC["Population"],HIC["GDP per Capita"],shade=True,shade_lowest=False,cmap="Reds")
sns.kdeplot(MIC["Population"],MIC["GDP per Capita"],shade=True,shade_lowest=False,cmap="Blues")
sns.kdeplot(LIC["Population"],LIC["GDP per Capita"],shade=True,shade_lowest=False,cmap="Greens")
plt.show()
Finally, we might want to assign a legend. To do this we need to do three separate things. First we need to pick colors to use for the legend, we will pick the third color for each color map by indexing the color maps by [2]. Next we need to create the shape for the legend, we will use patches and assign the colors and income level to them for our legend. Finally, we call the legend with this.
import matplotlib.patches as mpatches
hPlot = sns.kdeplot(HIC["Population"],HIC["GDP per Capita"],shade=True,shade_lowest=False,cmap="Reds")
mPlot = sns.kdeplot(MIC["Population"],MIC["GDP per Capita"],shade=True,shade_lowest=False,cmap="Blues")
lPlot = sns.kdeplot(LIC["Population"],LIC["GDP per Capita"],shade=True,shade_lowest=False,cmap="Greens")
r = sns.color_palette("Reds")[2]
b = sns.color_palette("Blues")[2]
g = sns.color_palette("Greens")[2]
red_patch = mpatches.Patch(color=r, label='HIC')
blue_patch = mpatches.Patch(color=b, label='MIC')
green_patch = mpatches.Patch(color=g, label='LIC')
plt.legend(handles=[red_patch,blue_patch,green_patch])
plt.show()
Source Code