-2

I am trying to plot wind speed and wind direction for multiple levels on one large series of subplots using plt.subplots().

I have:

fig, axes=plt.subplots(n=levels,figsize=(20,30),sharex=True)
for i in range(levels):
     axes[i].plot(time,wind_speed[:,i])

How can I add the second y-axis on each subplot so I can plot wind speed and wind direction on the same plot for each level? I don't understand how do add a second axis second axes cannot be enumerated this way.

Each plot will have the same x-axis, but wind speed on a line plot (left y-axis) and wind direction as dots (right y-axis). twinx would work but Python does not like twinx when using iteration in a for loop.

I tried axes[0][i]=axes[i].twinx I also tried to do a another nested for loop with for j... to do axes[j]=axes[i].twinx. None of this worked.

Jonathon
  • 251
  • 1
  • 7
  • 20
  • Please unlock my question. The one you called a "duplicate" is nothing like I am asking. It has only thing plotted on each plot and I am asking about 2 datasets per plot. Please unlock. – Jonathon Apr 21 '20 at 13:24
  • Is your question about how to [`twinx`](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.twinx.html)? – BigBen Apr 21 '20 at 13:27
  • Yes. I have tried twinx on this in several ways but cannot figure how to do it with the for loop I have. – Jonathon Apr 21 '20 at 13:27
  • 3
    Please can you share a small example and describe the expected output? – yatu Apr 21 '20 at 13:27
  • 2
    "twinx would work but Python does not like twinx when using iteration in a for loop." What makes you say that? Can you post the corresponding code? – Keldorn Apr 21 '20 at 13:41

1 Answers1

1

With no info and limited understanding of your problem but I guess this might do:

the input argument: sharex = True allows you to keep the same axis across subplots.

My understanding is that within one plot you want a left and right y-axis:


fig, axes=plt.subplots(n=levels,figsize=(20,30),sharex=True)
for i in range(levels):
     axes[i].plot(time, wind_speed[:, i])
     ax2 = axes[i].twinx()
     ax2.plot(time, wind_direction[:, i])


CAPSLOCK
  • 6,243
  • 3
  • 33
  • 56
  • Thank you. I thought all "axes" had to have a [i] iteration but I guess I was overthinking – Jonathon Apr 21 '20 at 13:42
  • 2
    no prob. you are welcome. Next time try to post a small example of your data, you'd have had an answer in a sec from one of the other users. – CAPSLOCK Apr 21 '20 at 13:43