1

I'm fairly new to Python and matplotlib. I want to plot something and on the right hand plot a detail of the main plot. But I don't want to duplicate the plot explicitly, given the complexity of the actual plot

MWE

import numpy as np
import matplotlib.pyplot as plt

x=np.arange(0,10,0.01)
y=np.sin(x)

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(x,y)

# I WANT TO AVOID THIS LINE
ax2.plot(x,y)
# AND USE SOMETHING LIKE ax2=ax1

ax2.set_xlim([0.5,0.7])
ax2.set_ylim(np.sin(ax2.get_xlim()))
plt.show();

Thanks

1
  • 1
    Create a dedicated function that does all the plotting and pass it the axes instance both times, i.e. for both ax1 and ax2. Commented Apr 15, 2021 at 18:55

1 Answer 1

1

Thanks to @BigBen comment, I did the following

import numpy as np
import matplotlib.pyplot as plt

x=np.arange(0,10,0.01)
y=np.sin(x)

def plotty(x, y, ax):
    ax.plot(x,y)

fig, (ax1, ax2) = plt.subplots(1, 2)

plotty(x, y, ax1)

plotty(x, y, ax2)

ax2.set_xlim([0.5,0.7])
ax2.set_ylim(np.sin(ax2.get_xlim()))
plt.show();

My actual function computes PSD based on a list of parameters, putting several spectra on the same plot. This syntax is fairly elegant and compact.

Thanks

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

2 Comments

The function you define is totally unnecessary, just say, e.g., ax1.plot(x, y)
I agree. It's just an example. In my case, my plot is generated using 10 lines of ax1.plot(), calling several data series. I want to copy ax1 into ax2, and then reset the axis limits, to zoom into a smaller region of the whole plot. I don't want to write twice those 10 lines, which would be contained in my plotty function

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.