49

Using the examples from seaborn.pydata.org and the Python DataScience Handbook, I'm able to produce a combined distribution plot with the following snippet:

Code:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# some settings
sns.set_style("darkgrid")

# Create some data
data = np.random.multivariate_normal([0, 0], [[5, 2], [2, 2]], size=2000)
data = pd.DataFrame(data, columns=['x', 'y'])

# Combined distributionplot
sns.distplot(data['x'])
sns.distplot(data['y'])

Plot: enter image description here

How can I combine this setup with vertical lines so that I can illustrate thresholds like this:

enter image description here

I know I can do it with matplotlib like here Dynamic histogram subplots with line to mark target, but I really like the simplicity of seaborn plots and would like to know if it's possible to do it more elegantly (and yes, I know that seaborn builds on top of matplotlib).

Thank you for any suggestions!

vestland
  • 43,687
  • 29
  • 146
  • 249
  • 1
    Here is an associated answer, since `seaborn` is an API for `matplotlib`. [How to draw vertical lines on a given plot in matplotlib?](https://stackoverflow.com/questions/24988448) – Trenton McKinney Sep 23 '20 at 18:59

1 Answers1

78

Just use

plt.axvline(2.8, 0,0.17)

And the same for the other line

Here instead of 0.17 you can put the maxima of your distribution using some variable such as maxx = max(data) or something similar. 2.8 is the position on the x-axis. Oh remember that the y-value has to be in between 0 and 1 where 1 is the top of the plot. You can rescale your values accordingly. Another obvious option is simply

plt.plot([2.8, 2.8], [0, max(data)])
Sheldore
  • 35,129
  • 6
  • 43
  • 58
  • 1
    I hope it's okay to throw in a little follow-up question... Do you know how to add a title (and sub-title)? I don't see any such options in the parameters using `sns.distplot?` – vestland Sep 14 '18 at 15:33
  • 2
    plt.title(“Title”) and plt.suptitle(“Sub title”) – Sheldore Sep 14 '18 at 15:35
  • 3
    I've got to admit I'm tempted to delete the question since it turned out to be a downvote magnet. But your suggestions really yanked me out of a false assumption that I was somehow bound to the parameters of sns.distplot and unable to use approaches such as plt.title() directly. To me, this is a real gamechanger with regards to seaborn and matplotlib. So thanks again for your assistance! – vestland Sep 14 '18 at 16:58
  • 6
    Note that `plt.axvline(x)` will draw a bar across the entire height of the plot at the value of x. You can also set the line color, line style etc… see https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.axvline.html – Michel Floyd Jul 26 '19 at 14:38
  • 4
    How to add a legend for the distplot line and the vertical ones though? – Newbielp May 14 '20 at 15:39