4.5.4 Density plot

Density plots are a commonly used tool to visualize the distribution of a continuous variable.

mpg = sns.load_dataset('mpg')   # load  the  embedded  dataset

1. Simple Density Chart

# Draw Density Plot

sns.kdeplot(mpg.loc[mpg["cylinders"] == 4, "mpg"], shade=True, color="g", label="Cyl=4", alpha=.7)
sns.kdeplot(mpg.loc[mpg["cylinders"] == 5, "mpg"], shade=True, color="deeppink", label= "Cyl=5", alpha=.7)
sns.kdeplot(mpg.loc[mpg["cylinders"] == 6, "mpg"], shade=True, color="dodgerblue", label= "Cyl=6", alpha=.7)
sns.kdeplot(mpg.loc[mpg["cylinders"] == 8, "mpg"], shade=True, color="orange", label= "Cyl=8", alpha=.7)
plt.title("Density Plot of MPG by n_Cylinders")

2. Density Curves with Histogram

3. Bandwidth Control (Bins)

Just like binsarrow-up-right in matplotlib, in seaborn, this is controlled using the bw argument of the kdeplot function.

Last updated