Reputation: 283
I can plot the joint distribution of two variables using jointplot
. However, I can't find a way to add arbitrary lines showing specific values on both dimensions.
For example, the following code works well in displaying the joint and marginal distributions
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(color_codes=True)
tips = sns.load_dataset("iris")
plot = sns.jointplot(x="sepal_length", y="sepal_width", data=tips,
kind="kde")
However, I can't find a way to include specific vertical and horizontal lines at pre-specified values. For example, including
plt.plot([6, 1.5], [6, 5], color="skyblue", lw=5, linestyle='solid', label="_not in legend")
generates a line on one of the marginals, but nothing on the jointplot
. Is there a way in which I could add, for example, a vertical and horizontal lines at specific values of sepal_length and sepal_width? (say, vertical line at 6 and horizontal line at 3) And, more in general, is it possible to make these lines based on specific statistics of the data? (mean, median of the different variables).
Thanks,
Upvotes: 8
Views: 8016
Reputation: 932
You can modify the main axes of a jointplot using ax_join. Through that you can use standard matplotlib.pyplot commands such as axvline and axhline:
import seaborn as sns
sns.set(color_codes=True)
tips = sns.load_dataset("iris")
plot = sns.jointplot(x="sepal_length",y="sepal_width",data=tips,kind="kde")
plot.ax_joint.axvline(x=6)
plot.ax_joint.axhline(y=3)
plot.ax_joint.set_xlim(4,8)
plot.ax_joint.set_ylim(2,4.5)
You could in fact also plot a general line not just a constant:
plot.ax_joint.plot([4,8], [2,5], 'b-', linewidth = 2)
For constant lines using stats you can use the pandas dataframe properties:
plot.ax_joint.axvline(x=tips.sepal_length.median(),linestyle='--')
plot.ax_joint.axhline(y=tips.sepal_width.mean(),linestyle='--')
You could also add lines to the marginal distribution using marg_x and marg_y:
plot.ax_marg_x.axvline(x=6)
plot.ax_marg_y.axhline(y=3)
It looks like this:
Upvotes: 20