从函数中返回一个子图

17

我希望您能在IPython Notebook中使用Matplotlib创建一个图形,并从一个函数中返回多个子图:

import matplotlib.pyplot as plt

%matplotlib inline

def create_subplot(data):
    more_data = do_something_on_data()  
    bp = plt.boxplot(more_data)
    # return boxplot?
    return bp

# make figure with subplots
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(10,5))

ax1 -> how can I get the plot from create_subplot() and put it on ax1?
ax1 -> how can I get the plot from create_subplot() and put it on ax2?

我知道可以直接将一个图形添加到坐标轴上:

ax1.boxplot(data)

但是我该如何从一个函数中返回一个图形并将其用作子图呢?

1个回答

28

通常,您会这样做:

def create_subplot(data, ax=None):
    if ax is None:
        ax = plt.gca()
    more_data = do_something_on_data()  
    bp = ax.boxplot(more_data)
    return bp

# make figure with subplots
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(10,5))
create_subplot(data, ax1)

你不能从一个函数中“返回绘图,并将其用作子图”。相反,你需要在子图中的坐标轴上绘制箱线图。

if ax is None 部分只是为了使传递显式坐标轴是可选的(如果没有,当前pyplot坐标轴将被使用,与调用plt.boxplot相同)。如果你愿意,可以省略它并要求指定特定的坐标轴。


3
好的,没问题!在开始时,理解绘图命令背后的图形对象和轴对象的“本质”可能会很困难。 - Martin Preusse
相反,您需要在子图中的轴上绘制箱线图。这是我需要进行心理转变的东西。谢谢。 - Mitchell van Zuylen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接