【问题标题】:Return a subplot from a function从函数返回子图
【发布时间】:2013-11-19 13:36:53
【问题描述】:

在 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)

但是我怎样才能从函数中返回一个图并将其用作子图呢?

【问题讨论】:

    标签: python matplotlib ipython


    【解决方案1】:

    通常,您会这样做:

    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. 相同)。如果您愿意,可以省略它并要求指定特定的轴。

    【讨论】:

    • 太好了,行得通!图形和轴对象的“性质”以及绘图命令背后的逻辑在开始时可能难以理解。
    • "相反,您需要在子图中的轴上绘制箱线图。"这就是我需要进行心理转变的东西。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2021-08-24
    • 2018-12-04
    相关资源
    最近更新 更多