【发布时间】: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 axarrreturn axarr.get_figure()return plt.axes()
但是,它们都返回类似的错误:AttributeError: 'AxesSubplot' object has no attribute 'plt'
返回绘图对象以便以后编辑的正确方法是什么?
【问题讨论】:
-
您是否尝试返回
fig = plt.gcf()? -
这里一切都是正确的,除了调用
plot.plt()而不是plot.plot()。愚蠢的错误;每个人都可能发生:)
标签: python matplotlib plot