我有一个函数可以包装 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()
我看到了一些关于这个问题的问题(如何从Pandas plot函数返回一个matplotlib.figure.Figure对象? 和 AttributeError: 'Figure' 对象没有 'plot' 属性),因此我尝试在函数结尾添加以下内容:
return axarr
return axarr.get_figure()
return plt.axes()
然而,它们都会返回类似的错误:AttributeError: 'AxesSubplot' object has no attribute 'plt'
什么是正确的方法来返回一个绘图对象以便稍后进行编辑?
fig = plt.gcf()
吗? - b-fgplot.plt()
而不是plot.plot()
。愚蠢的错误;任何人都可能犯错 :) - Liran Funaro