我目前正在尝试使用在函数中创建的传递轴对象,例如:
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
我的问题是,如何在另一个图中使用返回的轴对象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...
我尝试过如下声明:
ax_map.axes = ax1
虽然我的脚本没有崩溃,但我的轴空了。任何帮助将不胜感激!
答案 0 :(得分:1)
您正在尝试先绘制一个绘图,然后将该绘图作为另一个绘图中的子绘图(由subplot2grid
定义)。不幸的是,这是不可能的。另请参阅此帖子:How do I include a matplotlib Figure object as subplot?。
您必须先制作子图并将子图的轴传递给drawfig_1()
函数以绘制它。当然,drawfig_1()
需要修改。 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)