How to use Plot - Part 1 (Phoenix)

Keywords : Plot, Graph, Point, Sine, Cosine, PolyLine, PlotCanvas, PlotGraphics.


Demonstrating :

Tested py3.x, wx4.x and Win10.

Are you ready to use some samples ? ;)

Test, modify, correct, complete, improve and share your discoveries ! (!)


Plot :

First example

img_sample_one.png

   1 # sample_one.py
   2 
   3 """
   4 
   5 A simple example showing how to use lib.plot from wxPython.
   6 It is intended to be run as a standalone script via::
   7 user@host:.../site-packages/wx/lib/plot$ python examples/simple_example.py
   8 
   9 """
  10 
  11 import os
  12 import sys
  13 import wx
  14 from wx.lib import plot as wxplot
  15 
  16 # class MyPlotExample
  17 # class MyApp
  18 
  19 #---------------------------------------------------------------------------
  20 
  21 class MyPlotExample(wx.Frame):
  22     def __init__(self):
  23         wx.Frame.__init__(self, None,
  24                           title="Example of wx.lib.plot",
  25                           size=(400, 300))
  26 
  27         #------------
  28 
  29         # Return icons folder.
  30         self.icons_dir = wx.GetApp().GetIconsDir()
  31 
  32         #------------
  33 
  34         # Generate some Data.
  35         x_data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  36         y_data = [2, 4, 6, 4, 2, 5, 6, 7, 1]
  37 
  38         # Most items require data as a list of (x, y) pairs:
  39         #    [[1x, y1], [x2, y2], [x3, y3], ..., [xn, yn]]
  40         xy_data = list(zip(x_data, y_data))
  41 
  42         # Create your Poly object(s).
  43         # Use keyword args to set display properties.
  44         line = wxplot.PolySpline(
  45             xy_data,
  46             colour=wx.Colour(128, 128, 0),   # Color: olive
  47             width=3,
  48         )
  49 
  50         # Create your graphics object.
  51         graphics = wxplot.PlotGraphics([line])
  52 
  53         # Create your canvas.
  54         panel = wxplot.PlotCanvas(self)
  55 
  56         # Edit panel-wide settings.
  57         axes_pen = wx.Pen(wx.BLUE, 1, wx.PENSTYLE_LONG_DASH)
  58         panel.axesPen = axes_pen
  59 
  60         # Draw the graphics object on the canvas.
  61         panel.Draw(graphics)
  62 
  63         #------------
  64 
  65         # Create some sizers.
  66         mainSizer = wx.BoxSizer(wx.VERTICAL)
  67         checkSizer = wx.BoxSizer(wx.HORIZONTAL)
  68 
  69         # Layout the widgets.
  70         mainSizer.Add(panel, 1, wx.EXPAND | wx.ALL, 10)
  71         self.SetSizer(mainSizer)
  72 
  73         #------------
  74 
  75         # Simplified init method.
  76         self.SetProperties()
  77 
  78     #-----------------------------------------------------------------------
  79 
  80     def SetProperties(self):
  81         """
  82         ...
  83         """
  84 
  85         self.SetMinSize((400, 300))
  86         self.SetBackgroundColour(wx.WHITE)
  87 
  88         #------------
  89 
  90         frameIcon = wx.Icon(os.path.join(self.icons_dir,
  91                                          "wxwin.ico"),
  92                             type=wx.BITMAP_TYPE_ICO)
  93         self.SetIcon(frameIcon)
  94 
  95 #---------------------------------------------------------------------------
  96 
  97 class MyApp(wx.App):
  98     def OnInit(self):
  99 
 100         #------------
 101 
 102         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 103 
 104         #------------
 105 
 106         frame = MyPlotExample()
 107         self.SetTopWindow(frame)
 108         frame.Show(True)
 109 
 110         return True
 111 
 112     #-----------------------------------------------------------------------
 113 
 114     def GetInstallDir(self):
 115         """
 116         Return the installation directory for my application.
 117         """
 118 
 119         return self.installDir
 120 
 121 
 122     def GetIconsDir(self):
 123         """
 124         Return the icons directory for my application.
 125         """
 126 
 127         icons_dir = os.path.join(self.installDir, "icons")
 128         return icons_dir
 129 
 130 #---------------------------------------------------------------------------
 131 
 132 def main():
 133     app = MyApp(False)
 134     app.MainLoop()
 135 
 136 #---------------------------------------------------------------------------
 137 
 138 if __name__ == "__main__" :
 139     main()


Second example

img_sample_two.png

   1 # sample_two.py
   2 
   3 """
   4 
   5 Author : Mike Driscoll
   6 Created : Sept. 22, 2010
   7 Updated : Octo. 5, 2020 by Ecco
   8 Link : https://www.blog.pythonlibrary.org/2010/09/27/wxpython-pyplot-graphs-with-python/
   9 
  10 """
  11 
  12 import os
  13 import sys
  14 import wx
  15 from wx.lib.plot import PolyLine, PlotCanvas, PlotGraphics
  16 
  17 # def drawBarGraph
  18 # class MyGraph
  19 # class MyApp
  20 
  21 #---------------------------------------------------------------------------
  22 
  23 def drawBarGraph():
  24     # Bar graph
  25     points1=[(1,0), (1,10)]
  26     line1 = PolyLine(points1, colour='green', legend='Feb.', width=10)
  27     points1g=[(2,0), (2,4)]
  28     line1g = PolyLine(points1g, colour='red', legend='Mar.', width=10)
  29     points1b=[(3,0), (3,6)]
  30     line1b = PolyLine(points1b, colour='blue', legend='Apr.', width=10)
  31     points2=[(4,0), (4,12)]
  32     line2 = PolyLine(points2, colour='Yellow', legend='May', width=10)
  33     points2g=[(5,0), (5,8)]
  34     line2g = PolyLine(points2g, colour='orange', legend='June', width=10)
  35     points2b=[(6,0), (6,4)]
  36     line2b = PolyLine(points2b, colour='brown', legend='July', width=10)
  37     return PlotGraphics([line1, line1g, line1b, line2, line2g, line2b],
  38                         "Bar Graph - (Turn on Grid, Legend)", "Months",
  39                         "Number of Students")
  40 
  41 #---------------------------------------------------------------------------
  42 
  43 class MyGraph(wx.Frame):
  44     def __init__(self):
  45         wx.Frame.__init__(self, None, wx.ID_ANY,
  46                           'My first plot (to take over the world !)')
  47 
  48         #------------
  49 
  50         # Return icons folder.
  51         self.icons_dir = wx.GetApp().GetIconsDir()
  52 
  53         #------------
  54 
  55         # Add a panel so it looks the correct on all platforms.
  56         panel = wx.Panel(self, wx.ID_ANY)
  57 
  58         #------------
  59 
  60         # Create some sizers.
  61         mainSizer = wx.BoxSizer(wx.VERTICAL)
  62         checkSizer = wx.BoxSizer(wx.HORIZONTAL)
  63 
  64         #------------
  65 
  66         # Create the widgets.
  67         self.canvas = PlotCanvas(panel)
  68         self.canvas.Draw(drawBarGraph())
  69 
  70         toggleGrid = wx.CheckBox(panel, label="Show Grid")
  71         toggleGrid.SetValue(True)
  72         toggleGrid.Bind(wx.EVT_CHECKBOX, self.OnToggleGrid)
  73         
  74         toggleLegend = wx.CheckBox(panel, label="Show Legend")
  75         toggleLegend.SetValue(False)
  76         toggleLegend.Bind(wx.EVT_CHECKBOX, self.OnToggleLegend)
  77 
  78         #------------
  79 
  80         # Layout the widgets.
  81         mainSizer.Add(self.canvas, 1, wx.EXPAND | wx.ALL, 10)
  82         checkSizer.Add(toggleGrid, 0, wx.ALL, 5)
  83         checkSizer.Add(toggleLegend, 0, wx.ALL, 5)
  84         mainSizer.Add(checkSizer)
  85         panel.SetSizer(mainSizer)
  86 
  87         #------------
  88 
  89         # Simplified init method.
  90         self.SetProperties()
  91 
  92     #-----------------------------------------------------------------------
  93 
  94     def SetProperties(self):
  95         """
  96         ...
  97         """
  98 
  99         self.SetMinSize((450, 350))
 100         self.SetBackgroundColour(wx.WHITE)
 101 
 102         #------------
 103 
 104         frameIcon = wx.Icon(os.path.join(self.icons_dir,
 105                                          "wxwin.ico"),
 106                             type=wx.BITMAP_TYPE_ICO)
 107         self.SetIcon(frameIcon)
 108 
 109 
 110     def OnToggleGrid(self, event):
 111         """
 112         ...
 113         """
 114 
 115         # self.canvas.SetEnableGrid(event.IsChecked())
 116         self.canvas.enableGrid = event.IsChecked()
 117 
 118 
 119     def OnToggleLegend(self, event):
 120         """
 121         ...
 122         """
 123 
 124         # self.canvas.SetEnableLegend(event.IsChecked())
 125         self.canvas.enableLegend = event.IsChecked()
 126 
 127 #---------------------------------------------------------------------------
 128 
 129 class MyApp(wx.App):
 130     def OnInit(self):
 131 
 132         #------------
 133 
 134         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 135 
 136         #------------
 137 
 138         frame = MyGraph()
 139         self.SetTopWindow(frame)
 140         frame.Show(True)
 141 
 142         return True
 143 
 144     #-----------------------------------------------------------------------
 145 
 146     def GetInstallDir(self):
 147         """
 148         Return the installation directory for my application.
 149         """
 150 
 151         return self.installDir
 152 
 153 
 154     def GetIconsDir(self):
 155         """
 156         Return the icons directory for my application.
 157         """
 158 
 159         icons_dir = os.path.join(self.installDir, "icons")
 160         return icons_dir
 161 
 162 #---------------------------------------------------------------------------
 163 
 164 def main():
 165     app = MyApp(False)
 166     app.MainLoop()
 167 
 168 #---------------------------------------------------------------------------
 169 
 170 if __name__ == "__main__" :
 171     main()


Third example

img_sample_three.png

   1 # sample_three.py
   2 
   3 """
   4 
   5 Author : Mike Driscoll
   6 Created :  Sept. 22, 2010
   7 Updated : Octo. 5, 2020 by Ecco
   8 Link : https://www.blog.pythonlibrary.org/2010/09/27/wxpython-pyplot-graphs-with-python/
   9 
  10 """
  11 
  12 import os
  13 import sys
  14 import wx
  15 from wx.lib.plot import PolyLine, PlotCanvas, PlotGraphics
  16 
  17 # class MyGraph
  18 # class MyApp
  19 
  20 #---------------------------------------------------------------------------
  21 
  22 class MyGraph(wx.Frame):
  23     def __init__(self):
  24         wx.Frame.__init__(self, None, wx.ID_ANY,
  25                           'Plotting file data')
  26 
  27         #------------
  28 
  29         # Return icons folder.
  30         self.icons_dir = wx.GetApp().GetIconsDir()
  31 
  32         #------------
  33 
  34         # Add a panel so it looks the correct on all platforms.
  35         panel = wx.Panel(self, wx.ID_ANY)
  36 
  37         self.canvas = PlotCanvas(panel)
  38         self.canvas.Draw(self.CreatePlotGraphics())
  39 
  40         toggleGrid = wx.CheckBox(panel, label="Show Grid")
  41         toggleGrid.SetValue(True)
  42         toggleGrid.Bind(wx.EVT_CHECKBOX, self.OnToggleGrid)
  43 
  44         #------------
  45 
  46         sizer = wx.BoxSizer(wx.VERTICAL)
  47         checkSizer = wx.BoxSizer(wx.HORIZONTAL)
  48 
  49         sizer.Add(self.canvas, 1, wx.EXPAND | wx.ALL, 10)
  50         checkSizer.Add(toggleGrid, 0, wx.ALL, 5)
  51         sizer.Add(checkSizer)
  52         panel.SetSizer(sizer)
  53 
  54         #------------
  55 
  56         # Simplified init method.
  57         self.SetProperties()
  58 
  59     #-----------------------------------------------------------------------
  60 
  61     def SetProperties(self):
  62         """
  63         ...
  64         """
  65 
  66         self.SetMinSize((450, 360))
  67         self.SetBackgroundColour(wx.WHITE)
  68 
  69         #------------
  70 
  71         frameIcon = wx.Icon(os.path.join(self.icons_dir,
  72                                          "wxwin.ico"),
  73                             type=wx.BITMAP_TYPE_ICO)
  74         self.SetIcon(frameIcon)
  75 
  76 
  77     def ReadFile(self):
  78         """
  79         ...
  80         """
  81 
  82         # Normally you would want to pass a file path in, NOT hard code it !
  83         f = open("data.txt")
  84         # Skip the first two lines of text in the file.
  85         data = f.readlines()[2:-1]
  86         temps = []
  87         for line in data:
  88             parts = line.split(",")
  89             date = parts[0].split("-")
  90             day = date[2]
  91             points = [(day, parts[3]), (day, parts[1])]
  92             temps.append(points)
  93         return temps
  94 
  95 
  96     def CreatePlotGraphics(self):
  97         """
  98         ...
  99         """
 100 
 101         temps = self.ReadFile()
 102         lines = []
 103         for temp in temps:
 104             tempInt = int(temp[1][1])
 105             if tempInt < 60:
 106                 color = "blue"
 107             elif tempInt >=60 and tempInt <= 75:
 108                 color = "orange"
 109             else:
 110                 color = "red"
 111             lines.append(PolyLine(temp, colour=color, width=10))
 112 
 113         return PlotGraphics(lines, "Bar Graph of Temperatures",
 114                             "Days", "Temperatures")
 115 
 116 
 117     def OnToggleGrid(self, event):
 118         """
 119         ...
 120         """
 121 
 122         # self.canvas.SetEnableGrid(event.IsChecked())
 123         self.canvas.enableGrid = event.IsChecked()
 124 
 125 #---------------------------------------------------------------------------
 126 
 127 class MyApp(wx.App):
 128     def OnInit(self):
 129 
 130         #------------
 131 
 132         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 133 
 134         #------------
 135 
 136         frame = MyGraph()
 137         self.SetTopWindow(frame)
 138         frame.Show(True)
 139 
 140         return True
 141 
 142     #-----------------------------------------------------------------------
 143 
 144     def GetInstallDir(self):
 145         """
 146         Return the installation directory for my application.
 147         """
 148 
 149         return self.installDir
 150 
 151 
 152     def GetIconsDir(self):
 153         """
 154         Return the icons directory for my application.
 155         """
 156 
 157         icons_dir = os.path.join(self.installDir, "icons")
 158         return icons_dir
 159 
 160 #---------------------------------------------------------------------------
 161 
 162 def main():
 163     app = MyApp(False)
 164     app.MainLoop()
 165 
 166 #---------------------------------------------------------------------------
 167 
 168 if __name__ == "__main__" :
 169     main()


Fourth example

img_sample_four.png

   1 # -*- coding: utf-8 -*-
   2 # sample_four.py
   3 
   4 # pylint: disable=E1101, C0330, C0103
   5 #   E1101: Module X has no Y member
   6 #   C0330: Wrong continued indentation
   7 #   C0103: Invalid attribute/variable/method name
   8 
   9 """
  10 demo :
  11 =======
  12 
  13 This is a demo showing some of the capabilities of the :mod:`wx.lib.plot`
  14 package. It is intended to be run as a standalone script via::
  15 
  16   user@host:.../site-packages/wx/lib/plot$ python examples/demo.py
  17 
  18 """
  19 
  20 __docformat__ = "restructuredtext en"
  21 
  22 # Third Party
  23 import sys
  24 import os
  25 import wx
  26 from wx.lib import plot as wxplot
  27 
  28 # Needs NumPy
  29 try:
  30     import numpy as np
  31 except ImportError:
  32     msg = """
  33     This module requires the NumPy module, which could not be
  34     imported.  It probably is not installed (it's not part of the
  35     standard Python distribution). See the Numeric Python site
  36     (http://numpy.scipy.org) for information on downloading source or
  37     binaries, or just try `pip install numpy` and it will probably
  38     work."""
  39     raise ImportError("NumPy not found.\n" + msg)
  40 
  41 
  42 # ---------------------------------------------------------------------------
  43 ### Drawing Functions
  44 # ---------------------------------------------------------------------------
  45 def _draw1Objects():
  46     """Sin, Cos, and Points"""
  47     # 100 points sin function, plotted as green circles
  48     data1 = 2. * np.pi * np.arange(-200, 200) / 200.
  49     data1.shape = (200, 2)
  50     data1[:, 1] = np.sin(data1[:, 0])
  51     markers1 = wxplot.PolyMarker(data1,
  52                                  legend='Green Markers',
  53                                  colour='green',
  54                                  marker='circle',
  55                                  size=1,
  56                                  )
  57 
  58     # 50 points cos function, plotted as red line and markers
  59     data1 = 2. * np.pi * np.arange(-100, 100) / 100.
  60     data1.shape = (100, 2)
  61     data1[:, 1] = np.cos(data1[:, 0])
  62     lines = wxplot.PolySpline(data1, legend='Red Line', colour='red')
  63     markers3 = wxplot.PolyMarker(data1,
  64                                  legend='Red Dot',
  65                                  colour='red',
  66                                  marker='circle',
  67                                  size=1,
  68                                  )
  69 
  70     # A few more points...
  71     pi = np.pi
  72     pts = [(0., 0.), (pi / 4., 1.), (pi / 2, 0.), (3. * pi / 4., -1)]
  73     markers2 = wxplot.PolyMarker(pts,
  74                                  legend='Cross Legend',
  75                                  colour='blue',
  76                                  marker='cross',
  77                                  )
  78     line2 = wxplot.PolyLine(pts, drawstyle='steps-post')
  79 
  80     return wxplot.PlotGraphics([markers1, lines, markers3, markers2, line2],
  81                                "Graph Title",
  82                                "X Axis",
  83                                "Y Axis",
  84                                )
  85 
  86 
  87 def _draw2Objects():
  88     """Sin, Cos, Points, and lines between points"""
  89     # 100 points sin function, plotted as green dots
  90     data1 = 2. * np.pi * np.arange(200) / 200.
  91     data1.shape = (100, 2)
  92     data1[:, 1] = np.sin(data1[:, 0])
  93     line1 = wxplot.PolySpline(data1,
  94                               legend='Green Line',
  95                               colour='green',
  96                               width=6,
  97                               style=wx.PENSTYLE_DOT)
  98 
  99     # 25 points cos function, plotted as red dot-dash with steps.
 100     data1 = 2. * np.pi * np.arange(50) / 50.
 101     data1.shape = (25, 2)
 102     data1[:, 1] = np.cos(data1[:, 0])
 103     line2 = wxplot.PolyLine(data1,
 104                             legend='Red Line',
 105                             colour='red',
 106                             width=2,
 107                             style=wx.PENSTYLE_DOT_DASH,
 108                             drawstyle='steps-post',
 109                             )
 110 
 111     # data points for the 25pt cos function.
 112     pts2 = wxplot.PolyMarker(data1,
 113                              legend='Red Points',
 114                              colour='red',
 115                              size=1.5,
 116                              )
 117 
 118     # A few more points...
 119     pi = np.pi
 120     pts = [(0., 0.), (pi / 4., 1.), (pi / 2, 0.), (3. * pi / 4., -1)]
 121     markers1 = wxplot.PolyMarker(pts,
 122                                  legend='Cross Hatch Square',
 123                                  colour='blue',
 124                                  width=3,
 125                                  size=6,
 126                                  fillcolour='red',
 127                                  fillstyle=wx.CROSSDIAG_HATCH,
 128                                  marker='square',
 129                                  )
 130     marker_line = wxplot.PolyLine(pts,
 131                                   legend='Cross Hatch Square',
 132                                   colour='blue',
 133                                   width=3,
 134                                   )
 135 
 136     return wxplot.PlotGraphics([markers1, line1, line2, pts2, marker_line],
 137                                "Big Markers with Different Line Styles")
 138 
 139 
 140 def _draw3Objects():
 141     """Various Marker Types"""
 142     markerList = ['circle', 'dot', 'square', 'triangle', 'triangle_down',
 143                   'cross', 'plus', 'circle']
 144     m = []
 145     for i in range(len(markerList)):
 146         m.append(wxplot.PolyMarker([(2 * i + .5, i + .5)],
 147                                    legend=markerList[i],
 148                                    colour='blue',
 149                                    marker=markerList[i])
 150                                    )
 151     return wxplot.PlotGraphics(m,
 152                                title="Selection of Markers",
 153                                xLabel="Minimal Axis",
 154                                yLabel="No Axis")
 155 
 156 
 157 def _draw4Objects():
 158     """25,000 point line and markers"""
 159     # Points
 160     data1 = np.random.normal(loc=7.5e5, scale=70000, size=50000)
 161     data1.shape = (25000, 2)
 162     markers2 = wxplot.PolyMarker(data1,
 163                                  legend='Dots',
 164                                  colour='blue',
 165                                  marker='square',
 166                                  size=1,
 167                                  )
 168 
 169     # Line
 170     data1 = np.arange(5e5, 1e6, 10)
 171     data1.shape = (25000, 2)
 172     line1 = wxplot.PolyLine(data1, legend='Wide Line', colour='green', width=4)
 173 
 174     return wxplot.PlotGraphics([markers2, line1],
 175                                "25,000 Points",
 176                                "Value X",
 177                                "")
 178 
 179 
 180 def _draw5Objects():
 181     """Empty graph with axes but no points"""
 182     points = []
 183     line1 = wxplot.PolyLine(points,
 184                             legend='Wide Line',
 185                             colour='green',
 186                             width=5)
 187     return wxplot.PlotGraphics([line1],
 188                                "Empty Plot With Just Axes",
 189                                "Value X",
 190                                "Value Y")
 191 
 192 
 193 def _draw6Objects():
 194     """Faking a Bar graph"""
 195     points1 = [(1, 0), (1, 10)]
 196     line1 = wxplot.PolyLine(points1, colour='green', legend='Feb.', width=10)
 197     points1g = [(2, 0), (2, 4)]
 198     line1g = wxplot.PolyLine(points1g, colour='red', legend='Mar.', width=10)
 199     points1b = [(3, 0), (3, 6)]
 200     line1b = wxplot.PolyLine(points1b, colour='blue', legend='Apr.', width=10)
 201 
 202     points2 = [(4, 0), (4, 12)]
 203     line2 = wxplot.PolyLine(points2, colour='Yellow', legend='May', width=10)
 204     points2g = [(5, 0), (5, 8)]
 205     line2g = wxplot.PolyLine(points2g,
 206                              colour='orange',
 207                              legend='June',
 208                              width=10)
 209     points2b = [(6, 0), (6, 4)]
 210     line2b = wxplot.PolyLine(points2b, colour='brown', legend='July', width=10)
 211 
 212     return wxplot.PlotGraphics([line1, line1g, line1b, line2, line2g, line2b],
 213                                "Bar Graph - (Turn on Grid, Legend)",
 214                                "Months",
 215                                "Number of Students")
 216 
 217 
 218 def _draw7Objects():
 219     """Log10 on both axes"""
 220     x = np.arange(-1000, 1000, 1)
 221     y1 = 4.5 * x ** 2
 222     y2 = 2.2 * x ** 3
 223     points1 = np.transpose([x, y1])
 224     points2 = np.transpose([x, y2])
 225     line1 = wxplot.PolyLine(points1,
 226                             legend='quadratic',
 227                             colour='blue',
 228                             width=1)
 229     line2 = wxplot.PolyLine(points2, legend='cubic', colour='red', width=1)
 230     return wxplot.PlotGraphics([line1, line2],
 231                                "double log plot",
 232                                "Value X",
 233                                "Value Y")
 234 
 235 
 236 def _draw8Objects():
 237     """
 238     Box plot
 239     """
 240     data1 = np.array([np.NaN, 337, 607, 583, 512, 531, 558, 381, 621, 574,
 241                       538, 577, 679, 415, 454, 417, 635, 319, 350, 183,
 242                       863, 337, 607, 583, 512, 531, 558, 381, 621, 574,
 243                       538, 577, 679, 415, 454, 417, 635, 319, 350, 97])
 244     data2 = np.array([912, 337, 607, 583, 512, 531, 558, 381, 621, 574,
 245                       538, 532, 829, 82, 454, 417, 635, 319, 350, 183,
 246                       863, 337, 607, 583, 512, 531, 558, 866, 621, 574,
 247                       538, 577, 679, 415, 326, 417, 635, 319, 350, 97])
 248 
 249     data2 = data2 * 0.9
 250 
 251     data1 = np.array([(0, x) for x in data1])
 252     data2 = np.array([(1, x) for x in data2])
 253 
 254     data3 = np.random.gamma(2, 2, 500) * 30 + 100
 255     data3 = np.array([(2, x) for x in data3])
 256 
 257     boxplot = wxplot.BoxPlot(data1, legend="0.0: Weights")
 258     boxplot2 = wxplot.BoxPlot(data2, legend="1.0: Heights")
 259     boxplot3 = wxplot.BoxPlot(data3, legend="2.0: GammaDistribution")
 260     return wxplot.PlotGraphics([boxplot, boxplot2, boxplot3],
 261                                "Box Plot",
 262                                "",
 263                                "Value")
 264 
 265 def _draw9Objects():
 266     """
 267     Histogram
 268 
 269     The following must be true:
 270     len(bspec) = len(hist_data) + 1
 271     """
 272 
 273     data = 2.25 * np.random.randn(50) + 3
 274     heights, bins = np.histogram(data, bins=10)
 275 
 276     hist_fixed_binsize = wxplot.PolyHistogram(heights, bins)
 277 
 278     # Bins can also be arbitrary widths:
 279     hist_variable_binsize = wxplot.PolyHistogram(
 280         [2, 3, 4, 6, 3],
 281         [18, 19, 22, 25, 26, 27],
 282         fillcolour=wx.BLUE,
 283         edgewidth=2,
 284         edgecolour=wx.RED,
 285     )
 286 
 287     return wxplot.PlotGraphics(
 288         [hist_fixed_binsize, hist_variable_binsize],
 289         "Histogram with fixed binsize (left) and variable binsize (right)",
 290         "Value",
 291         "Count",
 292     )
 293 
 294 
 295 def _draw10Objects():
 296     """
 297     A real bar graph
 298     """
 299     bar_height = np.array([1, 5, 8, 16, 12, 15, 18, 23, 4, 7, 9, 6])
 300     bar_location = np.array([0, 2, 4, 6, 8, 10, 11, 12, 16, 20, 30])
 301     data = list(zip(bar_location, bar_height))
 302     bars = [wxplot.PolyBars(data)]
 303 
 304     return wxplot.PlotGraphics(bars, "Histogram", "XValue", "Count")
 305 
 306 
 307 # ---------------------------------------------------------------------------
 308 ### Demo Application
 309 # ---------------------------------------------------------------------------
 310 class PlotDemoApp(object):
 311     def __init__(self):
 312         self.app = wx.App()
 313         self.frame = PlotDemoMainFrame(None, -1, "PlotCanvas (demo)")
 314         self.frame.Show(True)
 315         self.app.MainLoop()
 316 
 317 
 318 class PlotDemoMainFrame(wx.Frame):
 319     # -----------------------------------------------------------------------
 320     ### UI Initialization
 321     # -----------------------------------------------------------------------
 322     def __init__(self, parent, wxid, title):
 323         wx.Frame.__init__(self, parent, wxid, title,
 324                           wx.DefaultPosition, (800, 600))
 325 
 326         frameIcon = wx.Icon("./icons/wxwin.ico")
 327         self.SetIcon(frameIcon)
 328 
 329         # Now Create the menu bar and items
 330         self.mainmenu = wx.MenuBar()
 331 
 332         self._init_file_menu()
 333         self._init_plot_menu()
 334         self._init_options_menu()
 335         self._init_help_menu()
 336 
 337         self.SetMenuBar(self.mainmenu)
 338 
 339         # A status bar to tell people what's happening
 340         self.CreateStatusBar(1)
 341 
 342         self.client = wxplot.PlotCanvas(self)
 343         # define the function for drawing pointLabels
 344 #        self.client.SetPointLabelFunc(self.DrawPointLabel)
 345         self.client.pointLabelFunc = self.DrawPointLabel
 346         # Create mouse event for showing cursor coords in status bar
 347         self.client.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
 348         # Show closest point when enabled
 349         self.client.canvas.Bind(wx.EVT_MOTION, self.OnMotion)
 350 
 351         self.OnPlotDraw1(None)
 352 
 353         wx.CallAfter(wx.MessageBox,
 354                      "Various plot types can be shown using the Plot menu. " +
 355                      "Check out the Options menu too.",
 356                      "wx.lib.plot Demo")
 357 
 358     def _init_file_menu(self):
 359         """ Create the "File" menu items. """
 360         menu = wx.Menu()
 361         menu.Append(200, 'Page Setup...', 'Setup the printer page')
 362         self.Bind(wx.EVT_MENU, self.OnFilePageSetup, id=200)
 363         menu.Append(201, 'Print Preview...', 'Show the current plot on page')
 364         self.Bind(wx.EVT_MENU, self.OnFilePrintPreview, id=201)
 365         menu.Append(202, 'Print...', 'Print the current plot')
 366         self.Bind(wx.EVT_MENU, self.OnFilePrint, id=202)
 367         menu.Append(203, 'Save Plot...', 'Save current plot')
 368         self.Bind(wx.EVT_MENU, self.OnSaveFile, id=203)
 369         menu.Append(wx.ID_EXIT, 'E&xit', 'Enough of this already!')
 370         self.Bind(wx.EVT_MENU, self.OnFileExit, id=wx.ID_EXIT)
 371         self.mainmenu.Append(menu, '&File')
 372 
 373     def _init_plot_menu(self):
 374         """ Create the "Plot" menu items. """
 375         menu = wx.Menu()
 376         menu.Append(206, 'Draw1 - sin, cos',
 377                     'Draw Sin and Cos curves')
 378         self.Bind(wx.EVT_MENU, self.OnPlotDraw1, id=206)
 379         menu.Append(207, 'Draw2 - sin, cos, large joined markers',
 380                     'Draw Sin and Cos curves with some large joined makers')
 381         self.Bind(wx.EVT_MENU, self.OnPlotDraw2, id=207)
 382         menu.Append(208, 'Draw3 - various markers',
 383                     'Demo various markers')
 384         self.Bind(wx.EVT_MENU, self.OnPlotDraw3, id=208)
 385         menu.Append(209, 'Draw4 - 25k pts',
 386                     'Example of drawing many points quickly')
 387         self.Bind(wx.EVT_MENU, self.OnPlotDraw4, id=209)
 388         menu.Append(210, 'Draw5 - empty plot',
 389                     'An empty plot')
 390         self.Bind(wx.EVT_MENU, self.OnPlotDraw5, id=210)
 391         menu.Append(260, 'Draw6 - fake bar graph via lines',
 392                     'Fake a bar graph by using lines.')
 393         self.Bind(wx.EVT_MENU, self.OnPlotDraw6, id=260)
 394         menu.Append(261, 'Draw7 - log-log',
 395                     'Plot a Log-Log graph')
 396         self.Bind(wx.EVT_MENU, self.OnPlotDraw7, id=261)
 397         menu.Append(262, 'Draw8 - Box Plots',
 398                     'Show off some box plots')
 399         self.Bind(wx.EVT_MENU, self.OnPlotDraw8, id=262)
 400         menu.Append(263, 'Draw9 - Histogram',
 401                     'Plot a histogram')
 402         self.Bind(wx.EVT_MENU, self.OnPlotDraw9, id=263)
 403         menu.Append(264, 'Draw10 - real bar graph',
 404                     'Plot a real bar chart (not faked with lines)')
 405         self.Bind(wx.EVT_MENU, self.OnPlotDraw10, id=264)
 406 
 407         menu.AppendSeparator()
 408 
 409         menu.Append(211, '&Redraw', 'Redraw plots')
 410         self.Bind(wx.EVT_MENU, self.OnPlotRedraw, id=211)
 411         menu.Append(212, '&Clear', 'Clear canvas')
 412         self.Bind(wx.EVT_MENU, self.OnPlotClear, id=212)
 413         menu.Append(213, '&Scale', 'Scale canvas')
 414         self.Bind(wx.EVT_MENU, self.OnPlotScale, id=213)
 415 
 416         menu.AppendSeparator()
 417 
 418         menu.Append(225, 'Scroll Up 1', 'Move View Up 1 Unit')
 419         self.Bind(wx.EVT_MENU, self.OnScrUp, id=225)
 420         menu.Append(230, 'Scroll Rt 2', 'Move View Right 2 Units')
 421         self.Bind(wx.EVT_MENU, self.OnScrRt, id=230)
 422         menu.Append(235, '&Plot Reset', 'Reset to original plot')
 423         self.Bind(wx.EVT_MENU, self.OnReset, id=235)
 424 
 425         self.mainmenu.Append(menu, '&Plot')
 426 
 427 
 428     def _init_options_menu(self):
 429         """ Create the "Options" menu items. """
 430         menu = wx.Menu()
 431 
 432         menu.Append(214, 'Enable &Zoom',
 433                     'Enable Mouse Zoom', kind=wx.ITEM_CHECK)
 434         self.Bind(wx.EVT_MENU, self.OnEnableZoom, id=214)
 435 
 436         menu.Append(217, 'Enable &Drag',
 437                     'Activates dragging mode', kind=wx.ITEM_CHECK)
 438         self.Bind(wx.EVT_MENU, self.OnEnableDrag, id=217)
 439 
 440         item = menu.Append(-1, 'Enable &Scrollbars (if needed)',
 441                     'Enable Scrollbars (if needed)', kind=wx.ITEM_CHECK)
 442         self.Bind(wx.EVT_MENU, self.OnEnableScrollbars, item)
 443 
 444         menu.Append(222, 'Enable &Point Label',
 445                     'Show Closest Point', kind=wx.ITEM_CHECK)
 446         self.Bind(wx.EVT_MENU, self.OnEnablePointLabel, id=222)
 447 
 448         menu.Append(223, 'Enable &Anti-Aliasing',
 449                     'Smooth output', kind=wx.ITEM_CHECK)
 450         self.Bind(wx.EVT_MENU, self.OnEnableAntiAliasing, id=223)
 451 
 452         menu.Append(224, 'Enable &High-Resolution AA',
 453                     'Draw in higher resolution', kind=wx.ITEM_CHECK)
 454         self.Bind(wx.EVT_MENU, self.OnEnableHiRes, id=224)
 455 
 456         menu.AppendSeparator()
 457 
 458         menu.Append(226, 'Enable Center Lines',
 459                     'Draw center lines', kind=wx.ITEM_CHECK)
 460         self.Bind(wx.EVT_MENU, self.OnEnableCenterLines, id=226)
 461 
 462         menu.Append(227, 'Enable Diagonal Lines',
 463                     'Draw diagonal lines', kind=wx.ITEM_CHECK)
 464         self.Bind(wx.EVT_MENU, self.OnEnableDiagonals, id=227)
 465 
 466         menu.Append(220, 'Enable &Legend',
 467                     'Turn on Legend', kind=wx.ITEM_CHECK)
 468         self.Bind(wx.EVT_MENU, self.OnEnableLegend, id=220)
 469 
 470         ### SubMenu for Grid
 471         submenu = wx.Menu()
 472         self.gridSubMenu = submenu
 473 
 474         submenu.AppendCheckItem(2151, "X Gridlines", "Enable X gridlines")
 475         submenu.AppendCheckItem(2152, "Y Gridlines", "Enable Y gridlines")
 476         submenu.AppendCheckItem(2153, "All Gridlines", "Enable All gridlines")
 477         submenu.Check(2151, True)
 478         submenu.Check(2152, True)
 479         submenu.Check(2153, True)
 480 
 481         self.Bind(wx.EVT_MENU, self.OnEnableGridX, id=2151)
 482         self.Bind(wx.EVT_MENU, self.OnEnableGridY, id=2152)
 483         self.Bind(wx.EVT_MENU, self.OnEnableGridAll, id=2153)
 484 
 485         menu.AppendSubMenu(submenu, 'Enable Grid', 'Turn on Grid')
 486 
 487         ### SubMenu for Axes
 488         submenu = wx.Menu()
 489         submenu_items = ("Bottom", "Left", "Top", "Right",
 490                          "Bottom+Left", "All")
 491         self.axesSubMenu = submenu
 492         for _i, item in enumerate(submenu_items, 2401):
 493             submenu.AppendCheckItem(_i, item, "Enables {} axis".format(item))
 494             submenu.Check(_i, True)
 495 
 496         self.Bind(wx.EVT_MENU, self.OnEnableAxesBottom, id=2401)
 497         self.Bind(wx.EVT_MENU, self.OnEnableAxesLeft, id=2402)
 498         self.Bind(wx.EVT_MENU, self.OnEnableAxesTop, id=2403)
 499         self.Bind(wx.EVT_MENU, self.OnEnableAxesRight, id=2404)
 500         self.Bind(wx.EVT_MENU, self.OnEnableAxesBottomLeft, id=2405)
 501         self.Bind(wx.EVT_MENU, self.OnEnableAxesAll, id=2406)
 502 
 503         menu.AppendSubMenu(submenu, 'Enable Axes', 'Enables the display of the Axes')
 504 
 505         submenu = wx.Menu()
 506         submenu_items = ("Bottom", "Left", "Top", "Right")
 507         help_txt = "Enables {} axis values"
 508         self.axesValuesSubMenu = submenu
 509         for _i, item in enumerate(submenu_items, 2451):
 510             submenu.AppendCheckItem(_i, item, help_txt.format(item))
 511 
 512         submenu.Check(2451, True)
 513         submenu.Check(2452, True)
 514         submenu.Check(2453, False)
 515         submenu.Check(2454, False)
 516 
 517         self.Bind(wx.EVT_MENU, self.OnEnableAxesValuesBottom, id=2451)
 518         self.Bind(wx.EVT_MENU, self.OnEnableAxesValuesLeft, id=2452)
 519         self.Bind(wx.EVT_MENU, self.OnEnableAxesValuesTop, id=2453)
 520         self.Bind(wx.EVT_MENU, self.OnEnableAxesValuesRight, id=2454)
 521 
 522         menu.AppendSubMenu(submenu, 'Enable Axes Values', 'Enables the display of the axes values')
 523 
 524         submenu = wx.Menu()
 525         submenu_items = ("Bottom", "Left", "Top", "Right",
 526                          "Bottom+Left", "All")
 527         help_txt = "Enables {} ticks"
 528         self.ticksSubMenu = submenu
 529         for _i, item in enumerate(submenu_items, 2501):
 530             submenu.AppendCheckItem(_i, item, help_txt.format(item))
 531 
 532         submenu.Check(2501, False)
 533         submenu.Check(2502, False)
 534         submenu.Check(2503, False)
 535         submenu.Check(2504, False)
 536 
 537         self.Bind(wx.EVT_MENU, self.OnEnableTicksBottom, id=2501)
 538         self.Bind(wx.EVT_MENU, self.OnEnableTicksLeft, id=2502)
 539         self.Bind(wx.EVT_MENU, self.OnEnableTicksTop, id=2503)
 540         self.Bind(wx.EVT_MENU, self.OnEnableTicksRight, id=2504)
 541         self.Bind(wx.EVT_MENU, self.OnEnableTicksBottomLeft, id=2505)
 542         self.Bind(wx.EVT_MENU, self.OnEnableTicksAll, id=2506)
 543 
 544         menu.AppendSubMenu(submenu, 'Enable Ticks','Enables the display of the ticks')
 545 
 546         menu.Append(255, 'Enable Plot Title',
 547                     'Enables the plot title', kind=wx.ITEM_CHECK)
 548         self.Bind(wx.EVT_MENU, self.OnEnablePlotTitle, id=255)
 549         menu.Check(255, True)
 550 
 551         menu.Append(270, 'Enable Axes Labels',
 552                     'Enables the X and Y axes labels', kind=wx.ITEM_CHECK)
 553         self.Bind(wx.EVT_MENU, self.OnEnableAxesLabels, id=270)
 554         menu.Check(270, True)
 555 
 556         menu.Append(271, 'Enable Log-Y',
 557                     'Changes the Y axis to log10 scale', kind=wx.ITEM_CHECK)
 558         self.Bind(wx.EVT_MENU, self.OnLogY, id=271)
 559         menu.Append(272, 'Enable Log-X',
 560                     'Changes the X axis to log10 scale', kind=wx.ITEM_CHECK)
 561         self.Bind(wx.EVT_MENU, self.OnLogX, id=272)
 562 
 563         menu.Append(273, 'Enable Abs(X)',
 564                     'Applies absolute value transform to X axis',
 565                     kind=wx.ITEM_CHECK)
 566         self.Bind(wx.EVT_MENU, self.OnAbsX, id=273)
 567         menu.Append(274, 'Enable Abs(Y)',
 568                     'Applies absolute value transform to Y axis',
 569                     kind=wx.ITEM_CHECK)
 570         self.Bind(wx.EVT_MENU, self.OnAbsY, id=274)
 571 
 572         menu.AppendSeparator()
 573 
 574         menu.Append(231, 'Set Gray Background',
 575                     'Change background colour to gray')
 576         self.Bind(wx.EVT_MENU, self.OnBackgroundGray, id=231)
 577         menu.Append(232, 'Set &White Background',
 578                     'Change background colour to white')
 579         self.Bind(wx.EVT_MENU, self.OnBackgroundWhite, id=232)
 580         menu.Append(233, 'Set Red Label Text',
 581                     'Change label text colour to red')
 582         self.Bind(wx.EVT_MENU, self.OnForegroundRed, id=233)
 583         menu.Append(234, 'Set &Black Label Text',
 584                     'Change label text colour to black')
 585         self.Bind(wx.EVT_MENU, self.OnForegroundBlack, id=234)
 586 
 587         self.mainmenu.Append(menu, '&Options')
 588 
 589         self.plot_options_menu = menu
 590 
 591     def _init_help_menu(self):
 592         """ Create the "Help" menu items. """
 593         menu = wx.Menu()
 594         menu.Append(wx.ID_ABOUT, '&About', 'About this thing...')
 595         self.Bind(wx.EVT_MENU, self.OnHelpAbout, id=wx.ID_ABOUT)
 596         self.mainmenu.Append(menu, '&Help')
 597 
 598     # -----------------------------------------------------------------------
 599     ### Event Handling
 600     # -----------------------------------------------------------------------
 601 
 602 
 603     def OnMouseLeftDown(self, event):
 604         s = "Left Mouse Down at Point: (%.4f, %.4f)" % self.client.GetXY(
 605             event)
 606         self.SetStatusText(s)
 607         event.Skip()  # allows plotCanvas OnMouseLeftDown to be called
 608 
 609     def OnMotion(self, event):
 610         # show closest point (when enbled)
 611         if self.client.enablePointLabel:
 612             # make up dict with info for the pointLabel
 613             # I've decided to mark the closest point on the closest curve
 614             dlst = self.client.GetClosestPoint(
 615                 self.client.GetXY(event),
 616                 pointScaled=True,
 617             )
 618             if dlst != []:  # returns [] if none
 619                 curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst
 620                 # make up dictionary to pass to my user function (see
 621                 # DrawPointLabel)
 622                 mDataDict = {"curveNum": curveNum,
 623                              "legend": legend,
 624                              "pIndex": pIndex,
 625                              "pointXY": pointXY,
 626                              "scaledXY": scaledXY}
 627                 # pass dict to update the pointLabel
 628                 self.client.UpdatePointLabel(mDataDict)
 629         event.Skip()  # go to next handler
 630 
 631     def OnFilePageSetup(self, event):
 632         self.client.PageSetup()
 633 
 634     def OnFilePrintPreview(self, event):
 635         self.client.PrintPreview()
 636 
 637     def OnFilePrint(self, event):
 638         self.client.Printout()
 639 
 640     def OnSaveFile(self, event):
 641         self.client.SaveFile()
 642 
 643     def OnFileExit(self, event):
 644         self.Close()
 645 
 646 
 647     # -----------------------------------------------------------------------
 648     ### PlotDraw Events
 649     # -----------------------------------------------------------------------
 650     def OnPlotDraw1(self, event):
 651         """ Sin, Cos, and Points """
 652         self.resetDefaults()
 653         self.client.Draw(_draw1Objects())
 654 
 655     def OnPlotDraw2(self, event):
 656         """ Sin, Cos, Points, and lines between points """
 657         self.resetDefaults()
 658         self.client.Draw(_draw2Objects())
 659 
 660     def OnPlotDraw3(self, event):
 661         """ Various Marker Types """
 662         self.resetDefaults()
 663         self.client.SetFont(wx.Font(10,
 664                                     wx.FONTFAMILY_SCRIPT,
 665                                     wx.FONTSTYLE_NORMAL,
 666                                     wx.FONTWEIGHT_NORMAL)
 667                             )
 668         self.client.fontSizeAxis = 20
 669         self.client.fontSizeLegend = 12
 670         self.client.xSpec = 'min'
 671         self.client.ySpec = 'none'
 672         self.client.Draw(_draw3Objects())
 673 
 674     def OnPlotDraw4(self, event):
 675         """ 25,000 point line and markers """
 676         self.resetDefaults()
 677         drawObj = _draw4Objects()
 678         self.client.Draw(drawObj)
 679 # profile
 680 #        start = _time.perf_counter()
 681 # for x in range(10):
 682 # self.client.Draw(drawObj)
 683 ##        print("10x of Draw4 took: %f sec."%(_time.perf_counter() - start))
 684 # profile end
 685 
 686     def OnPlotDraw5(self, event):
 687         """ Empty plot with just axes """
 688         self.resetDefaults()
 689         drawObj = _draw5Objects()
 690         # make the axis X= (0,5), Y=(0,10)
 691         # (default with None is X= (-1,1), Y= (-1,1))
 692         self.client.Draw(drawObj, xAxis=(0, 5), yAxis=(0, 10))
 693 
 694     def OnPlotDraw6(self, event):
 695         """ Bar Graph Example """
 696         self.resetDefaults()
 697         # self.client.SetEnableLegend(True)   #turn on Legend
 698         # self.client.SetEnableGrid(True)     #turn on Grid
 699         self.client.xSpec = 'none'
 700         self.client.ySpec = 'auto'
 701         self.client.Draw(_draw6Objects(), xAxis=(0, 7))
 702 
 703     def OnPlotDraw7(self, event):
 704         """ log scale example """
 705         self.resetDefaults()
 706         self.plot_options_menu.Check(271, True)
 707         self.plot_options_menu.Check(272, True)
 708         self.client.logScale = (True, True)
 709         self.client.Draw(_draw7Objects())
 710 
 711     def OnPlotDraw8(self, event):
 712         """ Box Plot example """
 713         self.resetDefaults()
 714         self.client.Draw(_draw8Objects())
 715 
 716     def OnPlotDraw9(self, event):
 717         """ Histogram example """
 718         self.resetDefaults()
 719         self.client.Draw(_draw9Objects())
 720 
 721     def OnPlotDraw10(self, event):
 722         """ Bar Chart example """
 723         self.resetDefaults()
 724         self.client.Draw(_draw10Objects())
 725 
 726     def OnPlotRedraw(self, event):
 727         self.client.Redraw()
 728 
 729     def OnPlotClear(self, event):
 730         self.client.Clear()
 731 
 732     def OnPlotScale(self, event):
 733         if self.client.last_draw is not None:
 734             graphics, xAxis, yAxis = self.client.last_draw
 735             self.client.Draw(graphics, (1, 3.05), (0, 1))
 736 
 737     # -----------------------------------------------------------------------
 738     ### Other Events
 739     # -----------------------------------------------------------------------
 740     def OnScrUp(self, event):
 741         self.client.ScrollUp(1)
 742 
 743     def OnScrRt(self, event):
 744         self.client.ScrollRight(2)
 745 
 746     def OnReset(self, event):
 747         self.client.Reset()
 748 
 749     def OnHelpAbout(self, event):
 750         from wx.lib.dialogs import ScrolledMessageDialog
 751         about = ScrolledMessageDialog(self, __doc__, "About...")
 752         about.ShowModal()
 753 
 754     def OnBackgroundGray(self, event):
 755         self.client.SetBackgroundColour("#CCCCCC")
 756         self.client.Redraw()
 757 
 758     def OnBackgroundWhite(self, event):
 759         self.client.SetBackgroundColour("white")
 760         self.client.Redraw()
 761 
 762     def OnForegroundRed(self, event):
 763         self.client.SetForegroundColour("red")
 764         self.client.Redraw()
 765 
 766     def OnForegroundBlack(self, event):
 767         self.client.SetForegroundColour("black")
 768         self.client.Redraw()
 769 
 770     # -----------------------------------------------------------------------
 771     ### Enable Grid Events
 772     # -----------------------------------------------------------------------
 773     def _checkOtherGridMenuItems(self):
 774         """ check or uncheck the submenu items """
 775         self.gridSubMenu.Check(2151, self.client.enableGrid[0])
 776         self.gridSubMenu.Check(2152, self.client.enableGrid[1])
 777         self.gridSubMenu.Check(2153, all(self.client.enableGrid))
 778 
 779     def OnEnableGridX(self, event):
 780         old = self.client.enableGrid
 781         self.client.enableGrid = (event.IsChecked(), old[1])
 782         self._checkOtherGridMenuItems()
 783 
 784     def OnEnableGridY(self, event):
 785         old = self.client.enableGrid
 786         self.client.enableGrid = (old[0], event.IsChecked())
 787         self._checkOtherGridMenuItems()
 788 
 789     def OnEnableGridAll(self, event):
 790         self.client.enableGrid = event.IsChecked()
 791         self._checkOtherGridMenuItems()
 792         self.gridSubMenu.Check(2151, event.IsChecked())
 793         self.gridSubMenu.Check(2152, event.IsChecked())
 794 
 795     # -----------------------------------------------------------------------
 796     ### Enable Axes Events
 797     # -----------------------------------------------------------------------
 798     def _checkOtherAxesMenuItems(self):
 799         """ check or uncheck the submenu items """
 800         self.axesSubMenu.Check(2401, self.client.enableAxes[0])
 801         self.axesSubMenu.Check(2402, self.client.enableAxes[1])
 802         self.axesSubMenu.Check(2403, self.client.enableAxes[2])
 803         self.axesSubMenu.Check(2404, self.client.enableAxes[3])
 804         self.axesSubMenu.Check(2405, all(self.client.enableAxes[:2]))
 805         self.axesSubMenu.Check(2406, all(self.client.enableAxes))
 806 
 807     def OnEnableAxesBottom(self, event):
 808         old = self.client.enableAxes
 809         self.client.enableAxes = (event.IsChecked(), old[1], old[2], old[3])
 810         self._checkOtherAxesMenuItems()
 811 
 812     def OnEnableAxesLeft(self, event):
 813         old = self.client.enableAxes
 814         self.client.enableAxes = (old[0], event.IsChecked(), old[2], old[3])
 815         self._checkOtherAxesMenuItems()
 816 
 817     def OnEnableAxesTop(self, event):
 818         old = self.client.enableAxes
 819         self.client.enableAxes = (old[0], old[1], event.IsChecked(), old[3])
 820         self._checkOtherAxesMenuItems()
 821 
 822     def OnEnableAxesRight(self, event):
 823         old = self.client.enableAxes
 824         self.client.enableAxes = (old[0], old[1], old[2], event.IsChecked())
 825         self._checkOtherAxesMenuItems()
 826 
 827     def OnEnableAxesBottomLeft(self, event):
 828         checked = event.IsChecked()
 829         old = self.client.enableAxes
 830         self.client.enableAxes = (checked, checked, old[2], old[3])
 831         self._checkOtherAxesMenuItems()
 832 
 833     def OnEnableAxesAll(self, event):
 834         checked = event.IsChecked()
 835         self.client.enableAxes = (checked, checked, checked, checked)
 836         self._checkOtherAxesMenuItems()
 837 
 838     # -----------------------------------------------------------------------
 839     ### Enable Ticks Events
 840     # -----------------------------------------------------------------------
 841     def _checkOtherTicksMenuItems(self):
 842         """ check or uncheck the submenu items """
 843         self.ticksSubMenu.Check(2501, self.client.enableTicks[0])
 844         self.ticksSubMenu.Check(2502, self.client.enableTicks[1])
 845         self.ticksSubMenu.Check(2503, self.client.enableTicks[2])
 846         self.ticksSubMenu.Check(2504, self.client.enableTicks[3])
 847         self.ticksSubMenu.Check(2505, all(self.client.enableTicks[:2]))
 848         self.ticksSubMenu.Check(2506, all(self.client.enableTicks))
 849 
 850     def OnEnableTicksBottom(self, event):
 851         old = self.client.enableTicks
 852         self.client.enableTicks = (event.IsChecked(), old[1],
 853                                    old[2], old[3])
 854         self._checkOtherTicksMenuItems()
 855 
 856     def OnEnableTicksLeft(self, event):
 857         old = self.client.enableTicks
 858         self.client.enableTicks = (old[0], event.IsChecked(),
 859                                    old[2], old[3])
 860         self._checkOtherTicksMenuItems()
 861 
 862     def OnEnableTicksTop(self, event):
 863         old = self.client.enableTicks
 864         self.client.enableTicks = (old[0], old[1],
 865                                    event.IsChecked(), old[3])
 866         self._checkOtherTicksMenuItems()
 867 
 868     def OnEnableTicksRight(self, event):
 869         old = self.client.enableTicks
 870         self.client.enableTicks = (old[0], old[1],
 871                                    old[2], event.IsChecked())
 872         self._checkOtherTicksMenuItems()
 873 
 874     def OnEnableTicksBottomLeft(self, event):
 875         checked = event.IsChecked()
 876         old = self.client.enableTicks
 877         self.client.enableTicks = (checked, checked, old[2], old[3])
 878         self._checkOtherTicksMenuItems()
 879 
 880     def OnEnableTicksAll(self, event):
 881         checked = event.IsChecked()
 882         self.client.enableTicks = tuple([checked] * 4)
 883         self._checkOtherTicksMenuItems()
 884 
 885     # -----------------------------------------------------------------------
 886     ### Enable AxesValues Events
 887     # -----------------------------------------------------------------------
 888     def OnEnableAxesValuesBottom(self, event):
 889         old = self.client.enableAxesValues
 890         self.client.enableAxesValues = (event.IsChecked(), old[1],
 891                                         old[2], old[3])
 892 
 893     def OnEnableAxesValuesLeft(self, event):
 894         old = self.client.enableAxesValues
 895         self.client.enableAxesValues = (old[0], event.IsChecked(),
 896                                         old[2], old[3])
 897 
 898     def OnEnableAxesValuesTop(self, event):
 899         old = self.client.enableAxesValues
 900         self.client.enableAxesValues = (old[0], old[1],
 901                                         event.IsChecked(), old[3])
 902 
 903     def OnEnableAxesValuesRight(self, event):
 904         old = self.client.enableAxesValues
 905         self.client.enableAxesValues = (old[0], old[1],
 906                                         old[2], event.IsChecked())
 907 
 908     # -----------------------------------------------------------------------
 909     ### Other Enable Events
 910     # -----------------------------------------------------------------------
 911     def OnEnableZoom(self, event):
 912         self.client.enableZoom = event.IsChecked()
 913         if self.mainmenu.IsChecked(217):
 914             self.mainmenu.Check(217, False)
 915 
 916     def OnEnableDrag(self, event):
 917         self.client.enableDrag = event.IsChecked()
 918         if self.mainmenu.IsChecked(214):
 919             self.mainmenu.Check(214, False)
 920 
 921     def OnEnableScrollbars(self, event):
 922         self.client.showScrollbars = event.IsChecked()
 923 
 924     def OnEnableLegend(self, event):
 925         self.client.enableLegend = event.IsChecked()
 926 
 927     def OnEnablePointLabel(self, event):
 928         self.client.enablePointLabel = event.IsChecked()
 929 
 930     def OnEnableAntiAliasing(self, event):
 931         self.client.enableAntiAliasing = event.IsChecked()
 932 
 933     def OnEnableHiRes(self, event):
 934         self.client.enableHiRes = event.IsChecked()
 935 
 936     def OnEnablePlotTitle(self, event):
 937         self.client.enablePlotTitle = event.IsChecked()
 938 
 939     def OnEnableAxesLabels(self, event):
 940         self.client.enableAxesLabels = event.IsChecked()
 941 
 942     def OnEnableCenterLines(self, event):
 943         self.client.enableCenterLines = event.IsChecked()
 944 
 945     def OnEnableDiagonals(self, event):
 946         self.client.enableDiagonals = event.IsChecked()
 947 
 948     def OnLogX(self, event):
 949         self.client.logScale = (event.IsChecked(), self.client.logScale[1])
 950         self.client.Redraw()
 951 
 952     def OnLogY(self, event):
 953         self.client.logScale = (self.client.logScale[0], event.IsChecked())
 954         self.client.Redraw()
 955 
 956     def OnAbsX(self, event):
 957         self.client.absScale = (event.IsChecked(), self.client.absScale[1])
 958         self.client.Redraw()
 959 
 960     def OnAbsY(self, event):
 961         self.client.absScale = (self.client.absScale[0], event.IsChecked())
 962         self.client.Redraw()
 963 
 964     def resetDefaults(self):
 965         """Just to reset the fonts back to the PlotCanvas defaults"""
 966         self.client.SetFont(wx.Font(10,
 967                                     wx.FONTFAMILY_SWISS,
 968                                     wx.FONTSTYLE_NORMAL,
 969                                     wx.FONTWEIGHT_NORMAL)
 970                             )
 971         self.client.fontSizeAxis = 10
 972         self.client.fontSizeLegend = 7
 973         self.client.logScale = (False, False)
 974         self.client.xSpec = 'auto'
 975         self.client.ySpec = 'auto'
 976 
 977     def DrawPointLabel(self, dc, mDataDict):
 978         """
 979         This is the fuction that defines how the pointLabels are plotted
 980 
 981         :param dc: DC that will be passed
 982         :param mDataDict: Dictionary of data that you want to use
 983                           for the pointLabel
 984 
 985         As an example I have decided I want a box at the curve point
 986         with some text information about the curve plotted below.
 987         Any wxDC method can be used.
 988 
 989         """
 990         dc.SetPen(wx.Pen(wx.BLACK))
 991         dc.SetBrush(wx.Brush(wx.BLACK, wx.BRUSHSTYLE_SOLID))
 992 
 993         sx, sy = mDataDict["scaledXY"]  # scaled x,y of closest point
 994         # 10by10 square centered on point
 995         dc.DrawRectangle(sx - 5, sy - 5, 10, 10)
 996         px, py = mDataDict["pointXY"]
 997         cNum = mDataDict["curveNum"]
 998         pntIn = mDataDict["pIndex"]
 999         legend = mDataDict["legend"]
1000         # make a string to display
1001         s = "Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i" % (
1002             cNum, legend, px, py, pntIn)
1003         dc.DrawText(s, sx, sy + 1)
1004 
1005 
1006 def run_demo():
1007     """
1008     Run the :mod:`wx.lib.plot` demo application.
1009     """
1010     PlotDemoApp()
1011 
1012 
1013 if __name__ == '__main__':
1014     run_demo()


Download source

source.zip


Additional Information

Link :

https://www.blog.pythonlibrary.org/2010/09/27/wxpython-pyplot-graphs-with-python/

- - - - -

https://wiki.wxpython.org/TitleIndex

https://docs.wxpython.org/


Thanks to

Mike Driscoll (sample_two / three.py coding), the wxPython community...


About this page

Date (d/m/y) Person (bot) Comments :

05/10/20 - Ecco (Created page for wxPython Phoenix).


Comments

- blah, blah, blah....

How to use Plot - Part 1 (Phoenix) (last edited 2020-10-07 13:23:36 by Ecco)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.