如何切换 matplotlib 图形的可见性?
How to toggle visibility of matplotlib figures?
有没有办法让 matplotlib 图形消失并重新出现以响应某些事件? (即按键)
我试过使用 fig.set_visible(False)
,但这似乎对我没有任何作用。
简单的代码示例:
import matplotlib
import matplotlib.pyplot as plt
fig=matplotlib.pyplot.figure(figsize=(10, 10))
# Some other code will go here
def toggle_plot():
# This function is called by a keypress to hide/show the figure
fig.set_visible(not fig.get_visible()) # This doesn't work for me
plt.show()
我尝试这样做的原因是因为我在图中有一堆 plots/animations 运行 显示 运行 模拟的输出,但显示它们一直以来,我的电脑都变慢了很多。
有什么想法吗?
matplotlib 库中有一个 small guide to image toggling。如示例所示,我能够使用 set_visible
和 get_visible()
。 matplotlib gallery 示例中的调用是在 AxesImage
个实例上,而不是 Figure
个实例,如您的示例代码中所示。这是我对为什么它对您不起作用的猜测。
您必须调用 plt.draw()
才能实际实例化任何更改。这应该有效:
def toggle_plot():
# This function is called by a keypress to hide/show the figure
fig.set_visible(not fig.get_visible())
plt.draw()
您可以将 tkinter 库中的 Toplevel() 小部件与 matplotlib 后端一起使用。
这是一个完整的例子:
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
fig,(ax) = plt.subplots()
x = np.linspace(0, 2 * np.pi)
y = np.transpose([np.sin(x)])
ax.plot(y)
graph = Toplevel()
canvas = FigureCanvasTkAgg(fig,master=graph)
canvas.get_tk_widget().grid()
canvas.show()
import pdb; pdb.set_trace()
通话中:
graph.withdraw()
将隐藏情节,并且:
graph.deiconify()
会再次显示。
有没有办法让 matplotlib 图形消失并重新出现以响应某些事件? (即按键)
我试过使用 fig.set_visible(False)
,但这似乎对我没有任何作用。
简单的代码示例:
import matplotlib
import matplotlib.pyplot as plt
fig=matplotlib.pyplot.figure(figsize=(10, 10))
# Some other code will go here
def toggle_plot():
# This function is called by a keypress to hide/show the figure
fig.set_visible(not fig.get_visible()) # This doesn't work for me
plt.show()
我尝试这样做的原因是因为我在图中有一堆 plots/animations 运行 显示 运行 模拟的输出,但显示它们一直以来,我的电脑都变慢了很多。 有什么想法吗?
matplotlib 库中有一个 small guide to image toggling。如示例所示,我能够使用 set_visible
和 get_visible()
。 matplotlib gallery 示例中的调用是在 AxesImage
个实例上,而不是 Figure
个实例,如您的示例代码中所示。这是我对为什么它对您不起作用的猜测。
您必须调用 plt.draw()
才能实际实例化任何更改。这应该有效:
def toggle_plot():
# This function is called by a keypress to hide/show the figure
fig.set_visible(not fig.get_visible())
plt.draw()
您可以将 tkinter 库中的 Toplevel() 小部件与 matplotlib 后端一起使用。
这是一个完整的例子:
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
fig,(ax) = plt.subplots()
x = np.linspace(0, 2 * np.pi)
y = np.transpose([np.sin(x)])
ax.plot(y)
graph = Toplevel()
canvas = FigureCanvasTkAgg(fig,master=graph)
canvas.get_tk_widget().grid()
canvas.show()
import pdb; pdb.set_trace()
通话中:
graph.withdraw()
将隐藏情节,并且:
graph.deiconify()
会再次显示。