Matplotlib返回绘图对象 [英] Matplotlib returning a plot object

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

问题描述

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

I have a function that wraps pyplot.plt so I can quickly create graphs with oft-used defaults:

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

但是,有时候我希望能够返回该图,因此我可以手动添加/编辑特定图形的内容.例如,我希望能够更改轴标签,或在调用该函数后在绘图中添加第二条线:

However, there are times where I'd want to be able to return the plot so I can manually add/edit things for a specific graph. For example, I want to be able to change the axis labels, or add a second line to the plot after calling the function:

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

我已经看到了一些有关此问题( AttributeError:"Figure"对象没有属性"plot" ),因此,我尝试在函数末尾添加以下内容:

I've seen a few questions on this (How to return a matplotlib.figure.Figure object from Pandas plot function? and AttributeError: 'Figure' object has no attribute 'plot') and as a result I've tried adding the following to the end of the function:

  • return axarr

return axarr.get_figure()

return plt.axes()

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

However, they all return a similar error: AttributeError: 'AxesSubplot' object has no attribute 'plt'

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

Whats the correct way to return a plot object so it can be edited later?

推荐答案

我认为该错误是不言自明的.没有诸如pyplot.plt之类的东西. plt是导入时pyplot的准标准缩写形式,即import matplotlib.pyplot as plt.

I think the error is pretty self-explanatory. There is no such thing as pyplot.plt, or similar. plt is the quasi standard abbreviated form of pyplot when being imported, i.e. import matplotlib.pyplot as plt.

关于问题,第一种方法return axarr是最通用的方法.您将获得一个轴或一组轴,并可以绘制到轴上.

Concerning the problem, the first approach, return axarr is the most versatile one. You get an axes, or an array of axes, and can plot to it.

代码可能看起来像

def plot_signal(x,y, ..., **kwargs):
    # Skipping a lot of other complexity her
    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()

这篇关于Matplotlib返回绘图对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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