在 matplotlib.pyplot 图形中使用传递的轴对象?

Ast*_*ibe 5 python axes matplotlib

我目前正在尝试使用在函数中创建的传递轴对象,例如:

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
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何在另一个图中使用返回的轴对象 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_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...
Run Code Online (Sandbox Code Playgroud)

我试过这样的陈述:

ax_map.axes = ax1
Run Code Online (Sandbox Code Playgroud)

尽管我的脚本没有崩溃,但我的轴却是空的。任何帮助,将不胜感激!

CT *_*Zhu 2

您尝试先绘制一个图,然后将该图作为另一个图的子图(由 定义subplot2grid)。不幸的是,这是不可能的。另请参阅这篇文章:How do I include a matplotlib Figure object as subplot?

您必须首先制作子图并将子图的轴传递给您的drawfig_1()函数来绘制它。当然,drawfig_1()还需要修改。例如:

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)
Run Code Online (Sandbox Code Playgroud)