写python程序matplotlib作图在wxpython界面上
下面是一个简单的例子,演示如何在wxPython界面上使用matplotlib作图。这个例子创建了一个简单的GUI,有一个按钮和一个matplotlib图形区域。当用户点击按钮时,程序会在图形区域中绘制一个简单的正弦波形。
import numpy as np
import matplotlib.pyplot as plt
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, title='Plotting in wxPython')
# Create a panel to hold the plot
self.panel = wx.Panel(self, wx.ID_ANY)
# Create a button
self.button = wx.Button(self.panel, wx.ID_ANY, 'Plot')
self.button.Bind(wx.EVT_BUTTON, self.on_plot)
# Create a figure and add a subplot
self.figure = plt.figure()
self.subplot = self.figure.add_subplot(111)
# Create a canvas to display the figure
self.canvas = FigureCanvas(self.panel, wx.ID_ANY, self.figure)
# Add the button and canvas to the panel
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.button, 0, wx.ALIGN_CENTER|wx.ALL, 5)
sizer.Add(self.canvas, 1, wx.EXPAND|wx.ALL, 5)
self.panel.SetSizer(sizer)
def on_plot(self, event):
# Generate some data
x = np.linspace(0, 2*np.pi, 1000)
y = np.sin(x)
# Clear the subplot and plot the data
self.subplot.clear()
self.subplot.plot(x, y)
# Refresh the canvas to update the plot
self.canvas.draw()
if __name__ == '__main__':
app = wx.App()
frame = MyFrame()
frame.Show()
app.MainLoop()
在这个例子中,我们首先创建一个MyFrame类,它继承自wx.Frame。在__init__方法中,我们创建了一个wx.Panel来容纳matplotlib图形,并添加了一个按钮和一个matplotlib图形区域。在on_plot方法中,我们生成一些数据并使用self.subplot.plot方法在图形区域中绘制正弦波形。最后,我们使用self.canvas.draw方法刷新canvas,更新图形。
需要注意的是,我们使用了FigureCanvas类来创建canvas。这个类是matplotlib提供的,用于在wxPython界面上显示matplotlib图形。
运行这个程序,点击按钮,就可以在界面上看到一个正弦波形。
原文地址: https://www.cveoy.top/t/topic/f1v 著作权归作者所有。请勿转载和采集!