我想在函数外部创建无花果,斧头对象,然后从函数内部修改斧头。当我的函数是典型的python函数时,此方法效果很好,但是当函数使用@interact装饰或由ipywidgets的交互包装时,此方法将失败。我很好奇为什么互动包装会影响斧头穿过的能力。
from ipywidgets import interact
from matplotlib import pyplot as plt
import numpy as np
fig, ax = plt.subplots(1)
def mod_ax(n=10):
x,y = np.random.rand(n), np.random.rand(n)
ax.scatter(x,y)
return
# The interact wrapped function will not modify ax
interact(mod_ax, n=20)
# However, the below line works fine to modify ax;
# comment out the interact line and comment in below line to see modified plot
# mod_ax(n=50)
plt.show()
使用交互包装功能时,它不会修改斧头。我曾尝试过将斧头当作一个参数,但还是没有运气。如果您在包装函数内部创建无花果,斧头,或者只是使用plt.plot而不是ax.plot,它就可以工作,但是我希望能够在包装函数外部创建无花果,斧头,然后仅修改其中的内容以加快更改交互滑块的渲染时间。任何意见,将不胜感激。
最佳答案
我正在使用JuPyter笔记本。当我使用%matplotlib inline
时,您的代码对我不起作用,但它与%matplotlib notebook
后端一起使用,但有以下两个更改(以注释#
突出显示)。之前曾问过类似的问题here
%matplotlib notebook # <--- Change 1
from ipywidgets import interact
from matplotlib import pyplot as plt
import numpy as np
fig, ax = plt.subplots(1)
def mod_ax(n=10):
x,y = np.random.rand(n), np.random.rand(n)
ax.scatter(x,y)
fig.canvas.draw() # <--- Change 1
return
interact(mod_ax, n=20)