1

I have a plot and I want to draw some vertical lines covering the whole range of the y-axis, without having to worry about the numerical values of that range. This matplotlib example demonstrates the functionality I'm looking for, and it works fine for me, but a very similar code does not. What am I doing wrong?

from matplotlib import pyplot as plt
import numpy as np

np.random.seed(19680801)
y = np.random.normal(scale=0.01, size=200).cumsum()
fig, ax = plt.subplots(1, 2, figsize=(12, 6))
ax[0].plot(y)
ax[0].vlines([25, 50, 100], [0], [0.1, 0.2, 0.3], color='C1')
ax[1].plot(y)
ax[1].vlines([25, 50, 100], [0], [0.1, 0.2, 0.3], color='C1')
ax[1].vlines([0], 0, 1, color='k', linestyle='dashed',
    transform=ax[1].get_xaxis_transform())

Expected: both plots have the same y-limits

Actual result: the plot on the right has the wrong limits

enter image description here

Using matplotlib 3.7.1 on python 3.11.3.

Ilya
  • 466
  • 2
  • 14
  • Not clear what is wrong in the result. Which vlines size are you not happy with? The orange one (but then, why explicitly specifying different sizes?), the dashed one? or all of them? – chrslg Aug 01 '23 at 22:47
  • 1
    https://matplotlib.org/stable/gallery/subplots_axes_and_figures/axhspan_demo.html#sphx-glr-gallery-subplots-axes-and-figures-axhspan-demo-py – Paul H Aug 01 '23 at 22:49
  • @PaulH Maybe write up an answer that outlines the three main methods for drawing straight lines in matplotlib, i.e. `axhline`/`axvline`, `axhspan`/`axvspan`, and `hlines`/`vlines`? I was going to do it, but considering you suggested it first, you have "first rights". – jared Aug 01 '23 at 23:04
  • @jared nah. go for it. i'll sit this one out – Paul H Aug 01 '23 at 23:12
  • 1
    `axvline` is a complete solution for the example as given, but unfortunately it only accepts a scalar as `x`. – Ilya Aug 01 '23 at 23:34
  • `ymin, ymax = ax.get_ylim()` and `ax.vlines(x=..., ymin=ymin, ymax=ymax, ...)`, or use `axvline` in a loop. – Trenton McKinney Aug 02 '23 at 02:57

1 Answers1

0

Set ymin and ymax to 0 and 1.

from matplotlib import pyplot as plt
import numpy as np

np.random.seed(19680801)
y = np.random.normal(scale=0.01, size=200).cumsum()
fig, ax = plt.subplots(1, 2, figsize=(12, 6))
ax[0].plot(y)
ax[0].vlines([25, 50, 100], 0, 1, color='C1', 
  transform=ax[0].get_xaxis_transform())
ax[1].plot(y)
ax[1].vlines([25, 50, 100], 0, 1, color='C1', 
  transform=ax[1].get_xaxis_transform())
ax[1].vlines([0], 0, 1, color='k', linestyle='dashed', 
  transform=ax[1].get_xaxis_transform())

As for the y-limits you can set them with:

ax[0].set_ylim([-0.05, 0.3])
ax[1].set_ylim([-0.05, 0.3])
binaryescape
  • 105
  • 6