【问题标题】:Matplotlib returning a plot objectMatplotlib 返回一个绘图对象
【发布时间】:2017-10-11 01:00:27
【问题描述】:

我有一个包装 pyplot.plt 的函数,因此我可以快速创建具有常用默认值的图表:

def plot_signal(time, signal, title='', xlab='', ylab='',
                line_width=1, alpha=1, color='k',
                subplots=False, show_grid=True, fig_size=(10, 5)):

    # Skipping a lot of other complexity here

    f, axarr = plt.subplots(figsize=fig_size)
    axarr.plot(time, signal, linewidth=line_width,
               alpha=alpha, color=color)
    axarr.set_xlim(min(time), max(time))
    axarr.set_xlabel(xlab)
    axarr.set_ylabel(ylab)
    axarr.grid(show_grid)

    plt.suptitle(title, size=16)
    plt.show()

但是,有时我希望能够返回绘图,以便可以手动添加/编辑特定图表的内容。例如,我希望能够更改轴标签,或者在调用函数后在绘图中添加第二行:

import numpy as np

x = np.random.rand(100)
y = np.random.rand(100)

plot = plot_signal(np.arange(len(x)), x)

plot.plt(y, 'r')
plot.show()

我已经看到了一些关于此的问题(How to return a matplotlib.figure.Figure object from Pandas plot function?AttributeError: 'Figure' object has no attribute 'plot'),因此我尝试在函数末尾添加以下内容:

  • return axarr

  • return axarr.get_figure()

  • return plt.axes()

但是,它们都返回类似的错误:AttributeError: 'AxesSubplot' object has no attribute 'plt'

返回绘图对象以便以后编辑的正确方法是什么?

【问题讨论】:

  • 您是否尝试返回fig = plt.gcf()
  • 这里一切都是正确的,除了调用plot.plt()而不是plot.plot()。愚蠢的错误;每个人都可能发生:)

标签: python matplotlib plot


【解决方案1】:

我认为这个错误是不言自明的。没有pyplot.plt 或类似的东西。 pltpyplot导入时的准标准简写形式,即import matplotlib.pyplot as plt

关于问题,第一种方法return axarr 是最通用的方法。你得到一个轴,或者一个轴数组,并且可以绘制到它。

代码可能如下所示:

def plot_signal(x,y, ..., **kwargs):
    # Skipping a lot of other complexity here
    f, ax = plt.subplots(figsize=fig_size)
    ax.plot(x,y, ...)
    # further stuff
    return ax

ax = plot_signal(x,y, ...)
ax.plot(x2, y2, ...)
plt.show()

【讨论】:

    【解决方案2】:

    这实际上是一个很好的问题,我花了好几年才弄清楚。一个很好的方法是将图形对象传递给您的代码并让您的函数添加一个轴,然后返回更新后的图形。这是一个例子:

    fig_size = (10, 5)
    f = plt.figure(figsize=fig_size)
    
    def plot_signal(time, signal, title='', xlab='', ylab='',
                    line_width=1, alpha=1, color='k',
                    subplots=False, show_grid=True, fig=f):
    
        # Skipping a lot of other complexity here
    
        axarr = f.add_subplot(1,1,1) # here is where you add the subplot to f
        plt.plot(time, signal, linewidth=line_width,
                   alpha=alpha, color=color)
        plt.set_xlim(min(time), max(time))
        plt.set_xlabel(xlab)
        plt.set_ylabel(ylab)
        plt.grid(show_grid)
        plt.title(title, size=16)
        
        return(f)
    f = plot_signal(time, signal, fig=f)
    f
    

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 2019-04-15
      • 1970-01-01
      • 2015-06-06
      • 2015-06-03
      • 2014-05-27
      • 2014-05-22
      • 2017-03-06
      • 2011-01-25
      相关资源
      最近更新 更多