Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn: How to add vertical lines to a distribution plot (sns.distplot)

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!

like image 447
vestland Avatar asked Sep 14 '18 15:09

vestland


People also ask

How do you insert a vertical line in Seaborn plot?

Seaborn's refline() function to add horizontal/vertical lines in subplots. To add a horizontal and vertical line we can use Seaborn's refline() function with x and y y co-ordinates for the locations of the horizontal and vertical lines.

How do I add a horizontal line in SNS plot?

The sns. barplot() function creates a bar plot between the columns 'sepal_width' and 'petal_width' and stores it in the variable, 'graph'. Next, the graph. axhline() function creates a horizontal line in the bar plot.


1 Answers

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)]) 
like image 62
Sheldore Avatar answered Sep 20 '22 13:09

Sheldore