1

I have a loop which for a certain condition (occurs e.g 3 times), I'd like to plot two dataset with twinx, so e.g at the end I have 3 plots on left-y and 3 plots on right-y. When I use the usual twinx, the loop takes incorrect values for right-y. How should I modify this example code to get them correct? Thank you very much!

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,10,100)
A=5

fig,ax=plt.subplots()

for i in range(0,10):
  A=i**2
  if(i%3==0):
    ax.plot(x,A*np.sin(x),'-ro')
    ax2=ax.twinx()
    ax2.plot(x,A*x,'-bp')
plt.show()

Here is the output. enter image description here

physiker
  • 889
  • 3
  • 16
  • 30

1 Answers1

2

You need to move your "ax2" definition outside the loop (see below). However, this makes seven plots, four on left, three on right. You need to update your "if" condition.

[![import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,10,100)
A=5

fig,ax=plt.subplots()
ax2=ax.twinx()

for i in range(0,10):
  A=i**2
  if(i%3==0):
    ax.plot(x,A*np.sin(x),'-ro')
    ax2.plot(x,A*x,'-bp')
plt.show()][1]][1]

New figure, is this right?

tnknepp
  • 5,888
  • 6
  • 43
  • 57
  • I am exactly in the same situation and I want to add legend. Can you add legend for each plot and display legend? – Joonho Park May 13 '20 at 10:31
  • @JoonhoPark I think what you want is covered in this answer: https://stackoverflow.com/a/5487005/1678467 – tnknepp May 13 '20 at 17:43