6

I am currently attempting to use passed axis object created in function, e.g.:

def drawfig_1():
    import matplotlib.pyplot as plt

    # Create a figure with one axis (ax1)
    fig, ax1 = plt.subplots(figsize=(4,2))

    # Plot some data
    ax1.plot(range(10))

    # Return axis object
    return ax1

My question is, how can I use the returned axis object, ax1, in another figure? For example, I would like to use it in this manner:

# Setup plots for analysis
fig2 = plt.figure(figsize=(12, 8))

# Set up 2 axes, one for a pixel map, the other for an image
ax_map = plt.subplot2grid((3, 3), (0, 0), rowspan=3)
ax_image = plt.subplot2grid((3, 3), (0, 1), colspan=2, rowspan=3)

# Plot the image
ax_psf.imshow(image, vmin=0.00000001, vmax=0.000001, cmap=cm.gray)

# Plot the map
????      <----- #I don't know how to display my passed axis here...

I've tried statements such as:

ax_map.axes = ax1

and although my script does not crash, my axis comes up empty. Any help would be appreciated!

1 Answer 1

2

You are trying to make a plot first and then put that plot as a subplot in another plot (defined by subplot2grid). Unfortunately, that is not possible. Also see this post: How do I include a matplotlib Figure object as subplot?.

You would have to make the subplot first and pass the axis of the subplot to your drawfig_1() function to plot it. Of course, drawfig_1() will need to be modified. e.g:

def drawfig_1(ax1):
    ax1.plot(range(10))
    return ax1

# Setup plots for analysis
fig2 = plt.figure(figsize=(12, 8))

# Set up 2 axes, one for a pixel map, the other for an image
ax_map = plt.subplot2grid((3, 3), (0, 0), rowspan=3)
ax_image = plt.subplot2grid((3, 3), (0, 1), colspan=2, rowspan=3)

# Plot the image
ax_image.imshow(image, vmin=0.00000001, vmax=0.000001, cmap=cm.gray)
# Plot the map:
drawfig_1(ax_map)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, @ct-zhu, that was it. I indeed had the logic reversed, and your solution worked for me.

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.