IPython/matplotlib:从函数返回子图

Mar*_*sse 8 python matplotlib ipython

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

我知道我可以直接在轴上添加一个图:

ax1.boxplot(data)
Run Code Online (Sandbox Code Playgroud)

但是如何从函数返回一个图并将其用作子图?

Joe*_*ton 18

通常,你会做这样的事情:

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

您不"从函数返回一个图并将其用作子图".相反,您需要在子图的轴上绘制箱线图.

if ax is None部分就在那里,因此传递显式轴是可选的(如果不是,将使用当前的pyplot轴,与调用相同plt.boxplot).如果您愿意,可以将其保留,并要求指定特定的轴.

  • 太好了,这有效!图形和轴对象的“性质”以及绘图命令背后的逻辑在一开始可能难以理解。 (2认同)