IPython/matplotlib:从函数返回子图 [英] IPython/matplotlib: Return subplot from function

查看:97
本文介绍了IPython/matplotlib:从函数返回子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在IPython Notebook中使用Matplotlib,我想创建一个具有从函数返回的子图的图形:

Using Matplotlib in an IPython Notebook, I would like to create a figure with subplots which are returned from a function:

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?

我知道我可以将绘图直接添加到轴上

I know that I can directly add a plot to an axis:

ax1.boxplot(data)

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

But how can I return a plot from a function and use it as a subplot?

推荐答案

通常,您会执行以下操作:

Typically, you'd do something like this:

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)

您不会从函数返回图并将其用作子图".取而代之的是,您需要在子图中的轴上绘制框图 .

You don't "return a plot from a function and use it as a subplot". Instead you need to plot the boxplot on the axes in the subplot.

if ax is None部分就在那儿,因此传递显式轴是可选的(否则,将使用当前的pyplot轴,与调用plt.boxplot相同.).如果需要,可以将其省略,并要求指定特定的轴.

The if ax is None portion is just there so that passing in an explicit axes is optional (if not, the current pyplot axes will be used, identical to calling plt.boxplot.). If you'd prefer, you can leave it out and require that a specific axes be specified.

这篇关于IPython/matplotlib:从函数返回子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆