IPython/matplotlib:从函数返回子块

2024-04-29 17:22:03 发布

您现在位置:Python中文网/ 问答频道 /正文

使用IPython笔记本中的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)

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


Tags: 函数datareturnplotmatplotlibonmorecreate
1条回答
网友
1楼 · 发布于 2024-04-29 17:22:03

通常,你会这样做:

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)

你不能“从一个函数返回一个图并将其用作子图”。相反,您需要在子块的轴上绘制框ploton

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

相关问题 更多 >