Using passed axis objects in a matplotlib.pyplot figure?
Asked Answered
P

1

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!

Plural answered 5/3, 2014 at 21:48 Comment(0)
M
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)
Morehead answered 5/3, 2014 at 22:17 Comment(1)
Thank you, @ct-zhu, that was it. I indeed had the logic reversed, and your solution worked for me.Plural

© 2022 - 2024 — McMap. All rights reserved.