1 | # using wxPython's wx.lib.plot.PlotCanvas to create a line graph |
---|
2 | # an added feature is that you can save the graph/plot to an image file |
---|
3 | |
---|
4 | import wx |
---|
5 | import wx.lib.plot |
---|
6 | # we are plotting a trig function and need math.sin() |
---|
7 | import math |
---|
8 | |
---|
9 | class MyFrame(wx.Frame): |
---|
10 | def __init__(self, parent, mytitle, mysize): |
---|
11 | wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize) |
---|
12 | |
---|
13 | # calculate the data lists of (x, y) tuples to be plotted |
---|
14 | data = [] |
---|
15 | x = 0 |
---|
16 | while True: |
---|
17 | y = math.sin(x) |
---|
18 | data.append((x, y)) |
---|
19 | # advance x a notch |
---|
20 | x += 0.01 |
---|
21 | # x is in radians for math.sin(x) |
---|
22 | if x > 3*math.pi: |
---|
23 | break |
---|
24 | |
---|
25 | # set up the plotting canvas |
---|
26 | plot_canvas = wx.lib.plot.PlotCanvas(self) |
---|
27 | # get client usable size of frame |
---|
28 | frame_size = self.GetClientSize() |
---|
29 | # needed for SaveFile() later |
---|
30 | plot_canvas.SetInitialSize(size=frame_size) |
---|
31 | # optionally allow scrolling |
---|
32 | plot_canvas.SetShowScrollbars(True) |
---|
33 | # optionally allow drag/draw rubberband area to zoom |
---|
34 | # use doubleclick to return to original |
---|
35 | # use right click to shrink |
---|
36 | plot_canvas.SetEnableZoom(True) |
---|
37 | # set the tick and axis label font size (default is 10 point) |
---|
38 | plot_canvas.SetFontSizeAxis(point=8) |
---|
39 | # set title font size (default is 15 point) |
---|
40 | plot_canvas.SetFontSizeTitle(point=10) |
---|
41 | |
---|
42 | # connect (x, y) points in data list with a line |
---|
43 | # also set color and width of line |
---|
44 | data_line = wx.lib.plot.PolyLine(data, colour='blue', width=1) |
---|
45 | |
---|
46 | # assign lines, title and axis labels |
---|
47 | gc = wx.lib.plot.PlotGraphics([data_line], |
---|
48 | "y = sin(x)", "x axis (radians)", "y axis") |
---|
49 | # set x and y axis ranges and then draw the plot |
---|
50 | plot_canvas.Draw(gc, xAxis=(0, 3*math.pi), yAxis=(-1.5, 1.5)) |
---|
51 | |
---|
52 | # optionally save the plot to an image file |
---|
53 | plot_canvas.SaveFile(fileName='sinecurve.jpg') |
---|
54 | |
---|
55 | |
---|
56 | app = wx.App(0) |
---|
57 | mytitle = "a wx.lib.plot.PlotCanvas Line Graph" |
---|
58 | width = 480 |
---|
59 | height = 300 |
---|
60 | MyFrame(None, mytitle, (width, height)).Show() |
---|
61 | app.MainLoop() |
---|