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

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

I am exactly in the same situation and I want to add legend. Can you add legend for each plot and display legend?
@JoonhoPark I think what you want is covered in this answer: stackoverflow.com/a/5487005/1678467

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.