【问题标题】:Why is 'figure' object not callable in nested function?为什么'figure'对象不能在嵌套函数中调用?
【发布时间】:2021-06-06 22:34:06
【问题描述】:

我正在调用一个函数,该函数创建一个带有两个子图的 matplotlib 图,然后绘制带有嵌套函数的子图。基本上是这样的:

def combined_plot(df_1, df_2):
    
    fig, ax = plt.subplots(1, 2, figsize=(14,4))
    plot_function_one(df_1, ax[0])
    plot_function_two(df_2, ax[1])
    
    return fig

当我打电话时,我收到这种类型的错误:'Figure' object is not callable。我以前在其他情况下做过这种事情,所以我很好奇潜在的原因是什么,或者这个错误在高层次上到底意味着什么。当我在 matplotlib 上下文中搜索错误时,我没有得到任何相关结果。

这是整个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-66-aeb1feab3628> in <module>
      4 subplot1_df = wrangling_subplot1_df(df2)
      5 subplot2_df, _ = wrangling_subplot2_df(df2)
----> 6 fig2 = combined_cpu_plot(subplot1_df, subplot2_df)

TypeError: 'Figure' object is not callable

注意:我不可能提供一个可重现的示例,因为代码和数据如此复杂,我几乎无法猜测多少简化会重现错误。所以我希望我在这个高级别所做的事情有问题——如果没有,这本身就是有帮助的。

我可以在函数调用之外运行函数体而不会出现错误,因此错误似乎来自将这些调用放入函数中。如果我运行该函数一次,则没有错误。如果我第二次运行它,它会抛出错误,并继续抛出它,直到我上去并重置函数。如果我连续运行两次,它会引发错误。所以如果我跑,这个,我得到了这个数字:

subplot1_df = wrangling_subplot1_df(df1)
subplot2_df, _ = wrangling_subplot2_df(df1)
fig1 = combined_cpu_plot(subplot1_df, subplot2_df)

但是如果我运行这个,我会得到类型错误:

subplot1_df = wrangling_subplot1_df(df1)
subplot2_df, _ = wrangling_subplot2_df(df1)
fig1 = combined_cpu_plot(subplot1_df, subplot2_df)

subplot1_df = wrangling_subplot1_df(df2)
subplot2_df, _ = wrangling_subplot2_df(df2)
fig2 = combined_cpu_plot(subplot1_df, subplot2_df)

所以我猜有些东西被遗忘了,第二次混淆了这个功能?我试过pyplot.close(),但这似乎并没有影响问题。

编辑:添加了整个错误。

编辑:添加了关于第二次运行的示例。

【问题讨论】:

  • 至少发布整个错误消息,包括堆栈跟踪......哪一行抛出错误?
  • 你在跟踪中看到的就是这个函数。我会把它扔进帖子里。
  • 你确定你没有在某处运行combined_cpu_plot = combined_cpu_plot(subplot1_df, subplot2_df)吗?
  • 这条消息告诉你的是combined_cpu_plot不是你认为的函数,而是一个情节(类型Figure)。在编写两个函数的过程中,您显然已经将调用combined_plot() 的结果分配给了变量combined_cpu_plot。该名称可能是该问题先前迭代的遗留物。如果 is 真的是一个函数,那么向我们展示它的定义。
  • 某处,您已将Figure 对象分配给变量combined_cpu_plot

标签: python function matplotlib typeerror figure


【解决方案1】:

不要将您的函数分配给具有相同名称的变量!在我的代码中,我将函数生成的图形分配给了一个同名变量,如下所示:

combined_cpu_plot = combined_cpu_plot(subplot1_df, subplot2_df)

这第一次运行良好,因为名称 combined_cpu_plot 现在包含函数返回的 matplotlib 图形。然而,第二次,语法尝试将图形作为函数调用,这就是错误显示图形对象不可可调用的原因。

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 2019-05-23
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    相关资源
    最近更新 更多