Seaborn 禁用图

Seaborn disable plot

我在 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()

我有两个问题:

有什么建议吗?提前致谢

如果您发布了一个可运行的小示例,将会有很大帮助。幸运的是,Google 帮助我弄清楚了所有需要的东西。基本上你需要设置某种变量来跟踪你是否点击了按钮。或者您可以使用 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 已弃用。我将其替换为推荐的创建应用程序对象的方法。