Search code examples
pythonplotfillarea

Filling Space Between Two Vertical Lines, Error: 'str' object has no attribute 'axvspan'


I am trying to find a way to fill the space between two vertical lines on 5 separate axes (the x coordinates of these lines are 400 and 600 respectively). However, it doesn't seem to like axvspan. I keep getting the error: 'str' object has no attribute 'axvspan'

Here is my code:

fig1, ax1 = plt.subplot_mosaic([['a)', 'a)'], ['b)', 'b)'], ['c)', 'c)'], ['d)', 'd)'], ['e)', 'e)']], figsize=(10, 25), sharex=True)

... REST OF CODE (i.e. plotting stuff) ...

for ax in ax1:
  ax.axvspan(400, 600, color='k', alpha=0.1, lw=0, zorder=-1)

My guess is that .axvspan doesn't work with plt.subplot_mosaic, any suggestions on how to fix this would be appreciated.


Solution

  • I worked out that the issue was that I was trying to assign the axvspan to ax, which in this case is a string of 'a)', 'b)' etc. I should rather have been assigning it to the actual axis (i.e.: ax1['a)'], ax1['b)'] etc).

    The following code therefore fixes the error:

    for ax in ax1: 
      ax1[ax].axvspan(400, 600, color='k', alpha=0.1, lw=0, zorder=-1)`