0

I am trying to draw a vertical line to a density plot from seaborn, and I want this line to reach the respective y-value at the curve. What I've tried:

np.random.seed(1)
a=np.random.normal(size=1000)
sns.kdeplot(a)
x, y = sns.kdeplot(a).get_lines()[0].get_data()
f = np.interp(1,x, y)
plt.axvline(1, ymax=f);

As you can see the result was not as desirable. I want the vertical line to reach the curve. What am I doing wrong?

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Oalvinegro
  • 458
  • 5
  • 21
  • 2
    `plt.vlines(1, 0, f)` would work here. `axvline` uses `ymax` as a fraction of the y-axis, not till as a y-value. Note that the given code works, but is far from recommended. `sns.kdeplot()` returns an `ax` (the subplot onto which the plot has been drawn), and shouldn't be called twice. – JohanC Apr 26 '23 at 21:03
  • 1
    `ax = sns.kdeplot(a, fill=False); x, y = ax.get_lines()[0].get_data(); f = np.interp(1, x, y); ax.vlines(1, 0, f)` would be more faithful to how matplotlib and seaborn are supposed to operate. – JohanC Apr 26 '23 at 21:09

0 Answers0