python - figure.show() 不显示
问题描述
我维护了一个实现该功能的精美绘图包plot_foobar()
。它返回带有绘图的图形,以便用户可以对它做一些事情,例如,将其保存到文件 ( savefig()
) 或显示它。不幸的是,show()
什么也没做。
MWE:
def plot_foobar():
# fancy plotting routing in a package
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1, 2], [3, 4])
return fig
# the user invokes the plotting function and gets back the figure object
fig = plot_foobar()
# saving the file works
# fig.savefig("out.png")
# :(
fig.show()
# works, but is clumsy:
# import matplotlib.pyplot as plt
# plt.show()
这是故意的吗?
如果是的话,我当然可以向用户询问 import matplotlib 并称plt.show()
自己为 - 这行得通。我宁愿避免暴露这些信息并强迫用户导入一些东西只是为了显示这个数字。是否有其他一些我可以返回的对象show()
,savefig()
等等?
解决方案
您可以向 Figure 实例添加一个装饰器以调用其中的 plt.show() :
def show_figure(f):
'''
Decorator to change fig.show() behavior.
'''
def wrapper():
import matplotlib.pyplot as plt
f() # call the original fig.show(), remove this line if there is no need to run fig.show()
plt.show()
return wrapper
def plot_foobar():
# fancy plotting routing in a package
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1, 2], [3, 4])
fig.show = show_figure(fig.show) # assign a decorator
return fig
# the user invokes the plotting function and gets back the figure object
fig = plot_foobar()
fig.show()
推荐阅读
- javascript - 设备方向未按预期工作
- go - 如何在循环外使用模板变量?
- ios - Xcode 无效的工具链。安装 Xcode 11 Beta 后
- templates - 当有多个模板时如何修改或删除 JESS 事实
- azure - 机器人模拟器错误:POST 400 directline.postActivity
- c# - 为什么 Image.FromFile 返回 System.Drawing.Bitmap?
- python - 向 solr 提出请求失败
- regex - 需要日期和时间格式的正则表达式
- awk - 如何使用 AWK 按计数过滤 OTU?
- android - 无法确定任务 ':app:preReleaseBuild' 的依赖关系