我在WxPython面板中嵌入了一个seaborn条形图,如下所示:
单击(大)按钮时绘制条形图。这就是我为实现它所做的:
class SamplePanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.figure = Figure()
self.ax = self.figure.add_subplot(111)
self.x = np.array(list('XYZV'))
self.y = np.array([200,400,300,20])
self.ax.set_ylabel("Sample numbers")
self.canvas = FigureCanvas(self, -1, self.figure)
self.button = wx.Button(self, label="Plot data", pos=(100,15))
self.button.Bind(wx.EVT_BUTTON, self.OnButtonClick)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.sizer.Add(self.button, 1, wx.LEFT | wx.TOP | wx.GROW)
self.SetSizer(self.sizer)
self.Fit()
def OnButtonClick(self,event):
sns.barplot(self.x, self.y, palette="BuGn_d", ax=self.ax)
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = wx.Frame(None, title='Sample bar plot')
panel = SamplePanel(frame)
frame.Show()
app.MainLoop()
我有两个问题:
单击按钮时,如何禁用/绘制绘图?也就是说,如果我单击按钮,则会出现该图。如果我再次点击,情节就会消失,我会回到一个空的原始视图,如下所示:
有什么建议吗?提前致谢
答案 0 :(得分:1)
如果您发布了一个小的可运行示例,那将会有很大帮助。幸运的是,谷歌帮助我找出所需的一切。基本上你需要设置某种变量来跟踪你是否点击了按钮。或者您可以使用wx.ToggleButton
代替常规wx.Button
。
要在不调整框架大小的情况下显示图表,只需拨打self.Layout()
即可。
要清除图形,您需要执行self.ax.cla()
或self.ax.clear()
之类的操作。这是一个适合我的完整示例:
import numpy as np
import seaborn as sns
import wx
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
class SamplePanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.toggled = False
self.figure = Figure()
self.ax = self.figure.add_subplot(111)
self.x = np.array(list('XYZV'))
self.y = np.array([200,400,300,20])
self.ax.set_ylabel("Sample numbers")
self.canvas = FigureCanvas(self, -1, self.figure)
self.button = wx.Button(self, label="Plot data", pos=(100,15))
self.button.Bind(wx.EVT_BUTTON, self.OnButtonClick)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.sizer.Add(self.button, 1, wx.LEFT | wx.TOP | wx.GROW)
self.SetSizer(self.sizer)
self.Fit()
def OnButtonClick(self, event):
if not self.toggled:
sns.barplot(self.x, self.y, palette="BuGn_d", ax=self.ax)
self.toggled = True
else:
self.ax.cla()
self.toggled = False
self.Layout()
if __name__ == "__main__":
app = wx.App(False)
frame = wx.Frame(None, title='Sample bar plot', size=(800,600))
panel = SamplePanel(frame)
frame.Show()
app.MainLoop()
另请注意,wx.PySimpleApp
已弃用。我把它换成了推荐的创建app对象的方法。