How to use Matplotlib - Part 1 (Phoenix)

Keywords : Figure, Axes3D, Line2D, Subplot, FigureCanvasWxAgg, NavigationToolbar2WxAgg, Matplotlib, Pie chart, Bar graph, Line plot, Bar plot, Scatter plot, Histogram, Box plot, Stem plot, Heatmap.


Demonstrating :

Tested py3.x, wx4.x and Win10.

Are you ready to use some samples ? ;)

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


Matplotlib :

First example

img_sample_one.png

   1 # sample_one.py
   2 
   3 """
   4 
   5 Link : https://matplotlib.org/3.3.1/gallery/user_interfaces/embedding_in_wx5_sgskip.html
   6 
   7 """
   8 
   9 import os
  10 import sys
  11 from numpy import arange, sin, pi
  12 import matplotlib
  13 matplotlib.use('WXAgg')
  14 from matplotlib.figure import Figure
  15 from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
  16 from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar2Wx
  17 import wx
  18 
  19 # class MyCanvasPanel
  20 # class MyFrame
  21 # class MyApp
  22 
  23 #---------------------------------------------------------------------------
  24 
  25 class MyCanvasPanel(wx.Panel):
  26     def __init__(self, parent):
  27         wx.Panel.__init__(self, parent)
  28 
  29         #------------
  30 
  31         # Simplified init method.
  32         self.CreateCtrls()
  33         self.DoLayout()
  34 
  35     #-----------------------------------------------------------------------
  36 
  37     def CreateCtrls(self):
  38         """
  39         ...
  40         """
  41 
  42         self.figure = Figure()
  43         self.axes = self.figure.add_subplot(111)
  44 
  45         #------------
  46 
  47         self.canvas = FigureCanvas(self, -1, self.figure)
  48 
  49         #------------
  50 
  51         self.toolbar = NavigationToolbar2Wx(self.canvas)
  52         self.toolbar.Realize()
  53 
  54 
  55     def DoLayout(self):
  56         """
  57         ...
  58         """
  59 
  60         sizer = wx.BoxSizer(wx.VERTICAL)
  61         sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
  62         sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
  63         self.SetSizer(sizer)
  64         self.Fit()
  65 
  66 
  67     def Draw(self):
  68         """
  69         ...
  70         """
  71 
  72         t = arange(0.0, 3.0, 0.01)
  73         s = sin(2 * pi * t)
  74         self.axes.plot(t, s)
  75 
  76 #---------------------------------------------------------------------------
  77 
  78 class MyFrame(wx.Frame):
  79     def __init__(self, title):
  80         wx.Frame.__init__(self, None, -1,
  81                           title,
  82                           size=(620, 620))
  83 
  84         #------------
  85 
  86         # Return icons folder.
  87         self.icons_dir = wx.GetApp().GetIconsDir()
  88 
  89         #------------
  90 
  91         # Simplified init method.
  92         self.SetProperties()
  93         self.CreateCtrls()
  94 
  95     #-----------------------------------------------------------------------
  96 
  97     def SetProperties(self):
  98         """
  99         ...
 100         """
 101 
 102         self.SetMinSize((620, 620))
 103 
 104         #------------
 105 
 106         frameIcon = wx.Icon(os.path.join(self.icons_dir,
 107                                          "wxwin.ico"),
 108                             type=wx.BITMAP_TYPE_ICO)
 109         self.SetIcon(frameIcon)
 110 
 111 
 112     def CreateCtrls(self):
 113         """
 114         ...
 115         """
 116 
 117         self.panel = MyCanvasPanel(self)
 118         self.panel.Draw()
 119 
 120 #---------------------------------------------------------------------------
 121 
 122 class MyApp(wx.App):
 123     def OnInit(self):
 124 
 125         #------------
 126 
 127         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 128 
 129         #------------
 130 
 131         frame = MyFrame("Sample one")
 132         self.SetTopWindow(frame)
 133         frame.Show(True)
 134 
 135         return True
 136 
 137     #-----------------------------------------------------------------------
 138 
 139     def GetInstallDir(self):
 140         """
 141         Return the installation directory for my application.
 142         """
 143 
 144         return self.installDir
 145 
 146 
 147     def GetIconsDir(self):
 148         """
 149         Return the icons directory for my application.
 150         """
 151 
 152         icons_dir = os.path.join(self.installDir, "icons")
 153         return icons_dir
 154 
 155 #---------------------------------------------------------------------------
 156 
 157 def main():
 158     app = MyApp(False)
 159     app.MainLoop()
 160 
 161 #---------------------------------------------------------------------------
 162 
 163 if __name__ == "__main__" :
 164     main()


Second example

img_sample_two.png

   1 # sample_two.py
   2 
   3 import os
   4 import sys
   5 import matplotlib
   6 matplotlib.use('WXAgg')
   7 from matplotlib.figure import Figure
   8 from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
   9 from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar2Wx
  10 import wx
  11 
  12 # class MyCanvasPanel
  13 # class MyFrame
  14 # class MyApp
  15 
  16 #---------------------------------------------------------------------------
  17 
  18 # Some data
  19 # Pie chart, where the slices will be ordered and plotted counter-clockwise :
  20 labels = 'Hogs', 'Frogs', 'Logs', 'Dogs'
  21 sizes = [15, 30, 45, 10]
  22 explode = (0, 0.1, 0, 0)  # Only "explode" the 2nd slice (i.e. 'Hogs').
  23 
  24 #---------------------------------------------------------------------------
  25 
  26 class MyCanvasPanel(wx.Panel):
  27     def __init__(self, parent):
  28         wx.Panel.__init__(self, parent)
  29 
  30         #------------
  31 
  32         # Simplified init method.
  33         self.CreateCtrls()
  34         self.DoLayout()
  35 
  36     #-----------------------------------------------------------------------
  37 
  38     def CreateCtrls(self):
  39         """
  40         ...
  41         """
  42 
  43         self.figure = Figure()
  44         self.axes = self.figure.add_subplot(111)
  45 
  46         #------------
  47 
  48         self.canvas = FigureCanvas(self, -1, self.figure)
  49 
  50         #------------
  51 
  52         self.toolbar = NavigationToolbar2Wx(self.canvas)
  53         self.toolbar.Realize()
  54 
  55 
  56     def DoLayout(self):
  57         """
  58         ...
  59         """
  60 
  61         sizer = wx.BoxSizer(wx.VERTICAL)
  62         sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
  63         sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
  64         self.SetSizer(sizer)
  65         self.Fit()
  66 
  67 
  68     def Draw(self):
  69         """
  70         ...
  71         """
  72 
  73         # Make figure and axes.
  74         self.axes.plot(1, 0)
  75 
  76         # To draw the pies.
  77         self.axes.pie(sizes,
  78                       labels=labels,
  79                       autopct='%1.1f%%',
  80                       textprops={'size': 'smaller'},
  81                       shadow=True,
  82                       radius=0.5,
  83                       startangle=90,
  84                       explode=explode)
  85 
  86         # Equal aspect ratio ensures that pie is drawn as a circle.
  87         self.axes.axis('equal')
  88 
  89         self.axes.legend(title="Hogs and dogs",
  90                          loc="center right",
  91                          bbox_to_anchor=(1, 0, 0, 1))
  92         self.axes.set_title("Raining hogs and dogs", bbox={'facecolor':'0.9', 'pad':8})
  93 
  94 #---------------------------------------------------------------------------
  95 
  96 class MyFrame(wx.Frame):
  97     def __init__(self, title):
  98         wx.Frame.__init__(self, None, -1,
  99                           title,
 100                           size=(640, 500))
 101 
 102         #------------
 103 
 104         # Return icons folder.
 105         self.icons_dir = wx.GetApp().GetIconsDir()
 106 
 107         #------------
 108 
 109         # Simplified init method.
 110         self.SetProperties()
 111         self.CreateCtrls()
 112 
 113     #-----------------------------------------------------------------------
 114 
 115     def SetProperties(self):
 116         """
 117         ...
 118         """
 119 
 120         self.SetMinSize((640, 500))
 121 
 122         #------------
 123 
 124         frameIcon = wx.Icon(os.path.join(self.icons_dir,
 125                                          "wxwin.ico"),
 126                             type=wx.BITMAP_TYPE_ICO)
 127         self.SetIcon(frameIcon)
 128 
 129 
 130     def CreateCtrls(self):
 131         """
 132         ...
 133         """
 134 
 135         self.panel = MyCanvasPanel(self)
 136         self.panel.Draw()
 137 
 138 #---------------------------------------------------------------------------
 139 
 140 class MyApp(wx.App):
 141     def OnInit(self):
 142 
 143         #------------
 144 
 145         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 146 
 147         #------------
 148 
 149         frame = MyFrame("Sample two")
 150         self.SetTopWindow(frame)
 151         frame.Show(True)
 152 
 153         return True
 154 
 155     #-----------------------------------------------------------------------
 156 
 157     def GetInstallDir(self):
 158         """
 159         Return the installation directory for my application.
 160         """
 161 
 162         return self.installDir
 163 
 164 
 165     def GetIconsDir(self):
 166         """
 167         Return the icons directory for my application.
 168         """
 169 
 170         icons_dir = os.path.join(self.installDir, "icons")
 171         return icons_dir
 172 
 173 #---------------------------------------------------------------------------
 174 
 175 def main():
 176     app = MyApp(False)
 177     app.MainLoop()
 178 
 179 #---------------------------------------------------------------------------
 180 
 181 if __name__ == "__main__" :
 182     main()


Third example

img_sample_three.png

   1 # sample_three.py
   2 
   3 """
   4 
   5 Link : https://white-wheels.hatenadiary.org/entry/20100327/p5
   6 
   7 """
   8 
   9 import os
  10 import sys
  11 import numpy as np
  12 import matplotlib
  13 matplotlib.interactive(True)
  14 matplotlib.use('WXAgg')
  15 from matplotlib.figure import Figure
  16 from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
  17 from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar2Wx
  18 from mpl_toolkits.mplot3d import Axes3D
  19 import wx
  20 
  21 # class MyCanvasPanel
  22 # class MyFrame
  23 # class MyApp
  24 
  25 #---------------------------------------------------------------------------
  26 
  27 class MyCanvasPanel(wx.Panel):
  28     def __init__(self, parent):
  29         wx.Panel.__init__(self, parent)
  30 
  31         #------------
  32 
  33         self.parent = parent
  34 
  35         #------------
  36 
  37         # Simplified init method.
  38         self.CreateCtrls()
  39         self.DoLayout()
  40 
  41     #-----------------------------------------------------------------------
  42 
  43     def CreateCtrls(self):
  44         """
  45         ...
  46         """
  47 
  48         self.figure = Figure()
  49         self.figure.set_facecolor((1.,1.,1.))
  50         self.axes = self.figure.add_subplot(111)
  51 
  52         #------------
  53 
  54         self.canvas = FigureCanvas(self, -1, self.figure)
  55         # self.canvas.SetBackgroundColour(wx.Colour(100, 100, 100))
  56 
  57         #------------
  58 
  59         self.toolbar = NavigationToolbar2Wx(self.canvas)
  60         self.toolbar.Realize()
  61 
  62         #------------
  63 
  64         self.SetSize()
  65 
  66 
  67     def SetSize(self):
  68         """
  69         ...
  70         """
  71 
  72         size = tuple(self.parent.GetClientSize())
  73         self.canvas.SetSize(740, 740)
  74         self.figure.set_size_inches(float(size[0])/self.figure.get_dpi(),
  75                                     float(size[1])/self.figure.get_dpi())
  76 
  77     def DoLayout(self):
  78         """
  79         ...
  80         """
  81 
  82         sizer = wx.BoxSizer(wx.VERTICAL)
  83         sizer.Add(self.canvas, 1, wx.RIGHT| wx.TOP | wx.GROW)
  84         sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
  85         self.SetSizer(sizer)
  86         self.Fit()
  87 
  88 
  89     def Draw(self):
  90         """
  91         ...
  92         """
  93 
  94         x = np.arange(-3, 3, 0.25)
  95         y = np.arange(-3, 3, 0.25)
  96         X, Y = np.meshgrid(x, y)
  97         Z = np.sin(X)+ np.cos(Y)
  98 
  99         ax = Axes3D(self.figure)
 100         ax.plot_wireframe(X, Y, Z)
 101 
 102 #---------------------------------------------------------------------------
 103 
 104 class MyFrame(wx.Frame):
 105     def __init__(self, title):
 106         wx.Frame.__init__(self, None, -1,
 107                           title,
 108                           size=(740, 740))
 109 
 110         #------------
 111 
 112         # Return icons folder.
 113         self.icons_dir = wx.GetApp().GetIconsDir()
 114 
 115         #------------
 116 
 117         # Simplified init method.
 118         self.SetProperties()
 119         self.CreateCtrls()
 120 
 121     #-----------------------------------------------------------------------
 122 
 123     def SetProperties(self):
 124         """
 125         ...
 126         """
 127 
 128         self.SetMinSize((740, 740))
 129 
 130         #------------
 131 
 132         frameIcon = wx.Icon(os.path.join(self.icons_dir,
 133                                          "wxwin.ico"),
 134                             type=wx.BITMAP_TYPE_ICO)
 135         self.SetIcon(frameIcon)
 136 
 137 
 138     def CreateCtrls(self):
 139         """
 140         ...
 141         """
 142 
 143         self.panel = MyCanvasPanel(self)
 144         self.panel.Draw()
 145 
 146 #---------------------------------------------------------------------------
 147 
 148 class MyApp(wx.App):
 149     def OnInit(self):
 150 
 151         #------------
 152 
 153         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 154 
 155         #------------
 156 
 157         frame = MyFrame("Sample three")
 158         self.SetTopWindow(frame)
 159         frame.Show(True)
 160 
 161         return True
 162 
 163     #-----------------------------------------------------------------------
 164 
 165     def GetInstallDir(self):
 166         """
 167         Return the installation directory for my application.
 168         """
 169 
 170         return self.installDir
 171 
 172 
 173     def GetIconsDir(self):
 174         """
 175         Return the icons directory for my application.
 176         """
 177 
 178         icons_dir = os.path.join(self.installDir, "icons")
 179         return icons_dir
 180 
 181 #---------------------------------------------------------------------------
 182 
 183 def main():
 184     app = MyApp(False)
 185     app.MainLoop()
 186 
 187 #---------------------------------------------------------------------------
 188 
 189 if __name__ == "__main__" :
 190     main()


Fourth example

img_sample_four.png

   1 # sample_four.py
   2 
   3 """
   4 
   5 Link : https://matplotlib.org/3.3.1/gallery/user_interfaces/embedding_in_wx5_sgskip.html
   6 
   7 """
   8 
   9 import os
  10 import sys
  11 import wx
  12 import wx.lib.agw.aui as aui
  13 import matplotlib as mpl
  14 from matplotlib.backends.backend_wxagg import (
  15     FigureCanvasWxAgg as FigureCanvas,
  16     NavigationToolbar2WxAgg as NavigationToolbar)
  17 
  18 # class MyPlot
  19 # class MyPlotNotebook
  20 # class Myframe
  21 # class MyApp
  22 
  23 #---------------------------------------------------------------------------
  24 
  25 class MyPlot(wx.Panel):
  26     def __init__(self, parent, id=-1, dpi=None, **kwargs):
  27         wx.Panel.__init__(self, parent, id=id, **kwargs)
  28 
  29         #------------
  30 
  31         self.figure = mpl.figure.Figure(dpi=dpi, figsize=(2, 2))
  32 
  33         #------------
  34 
  35         self.canvas = FigureCanvas(self, -1, self.figure)
  36 
  37         #------------
  38 
  39         self.toolbar = NavigationToolbar(self.canvas)
  40         self.toolbar.Realize()
  41 
  42         #------------
  43 
  44         sizer = wx.BoxSizer(wx.VERTICAL)
  45         sizer.Add(self.canvas, 1, wx.EXPAND)
  46         sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
  47         self.SetSizer(sizer)
  48 
  49 #---------------------------------------------------------------------------
  50 
  51 class MyPlotNotebook(wx.Panel):
  52     def __init__(self, parent, id=-1):
  53         wx.Panel.__init__(self, parent, id=id)
  54 
  55         #------------
  56 
  57         self.nb = aui.AuiNotebook(self)
  58 
  59         #------------
  60 
  61         sizer = wx.BoxSizer()
  62         sizer.Add(self.nb, 1, wx.EXPAND)
  63         self.SetSizer(sizer)
  64 
  65     #-----------------------------------------------------------------------
  66 
  67     def Add(self, name="plot"):
  68         """
  69         ...
  70         """
  71 
  72         page = MyPlot(self.nb)
  73         self.nb.AddPage(page, name)
  74         return page.figure
  75 
  76 #---------------------------------------------------------------------------
  77 
  78 class MyFrame(wx.Frame):
  79     def __init__(self, title):
  80         wx.Frame.__init__(self, None, -1,
  81                           title,
  82                           size=(450, 350))
  83 
  84         #------------
  85 
  86         # Return icons folder.
  87         self.icons_dir = wx.GetApp().GetIconsDir()
  88 
  89         #------------
  90 
  91         # Simplified init method.
  92         self.SetProperties()
  93         self.CreateCtrls()
  94 
  95     #-----------------------------------------------------------------------
  96 
  97     def SetProperties(self):
  98         """
  99         ...
 100         """
 101 
 102         self.SetMinSize((450, 350))
 103 
 104         #------------
 105 
 106         frameIcon = wx.Icon(os.path.join(self.icons_dir,
 107                                          "wxwin.ico"),
 108                             type=wx.BITMAP_TYPE_ICO)
 109         self.SetIcon(frameIcon)
 110 
 111 
 112     def CreateCtrls(self):
 113         """
 114         ...
 115         """
 116 
 117         plotter = MyPlotNotebook(self)
 118         axes1 = plotter.Add('figure 1').gca()
 119         axes1.plot([1, 2, 3], [2, 1, 4])
 120         axes2 = plotter.Add('figure 2').gca()
 121         axes2.plot([1, 2, 3, 4, 5], [2, 1, 4, 2, 3])
 122 
 123 #---------------------------------------------------------------------------
 124 
 125 class MyApp(wx.App):
 126     def OnInit(self):
 127 
 128         #------------
 129 
 130         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 131 
 132         #------------
 133 
 134         frame = MyFrame("Sample four")
 135         self.SetTopWindow(frame)
 136         frame.Show(True)
 137 
 138         return True
 139 
 140     #-----------------------------------------------------------------------
 141 
 142     def GetInstallDir(self):
 143         """
 144         Return the installation directory for my application.
 145         """
 146 
 147         return self.installDir
 148 
 149 
 150     def GetIconsDir(self):
 151         """
 152         Return the icons directory for my application.
 153         """
 154 
 155         icons_dir = os.path.join(self.installDir, "icons")
 156         return icons_dir
 157 
 158 #---------------------------------------------------------------------------
 159 
 160 def main():
 161     app = MyApp(False)
 162     app.MainLoop()
 163 
 164 #---------------------------------------------------------------------------
 165 
 166 if __name__ == "__main__" :
 167     main()


Download source

source.zip


Additional Information

Link :

https://matplotlib.org/3.1.3/gallery/pie_and_polar_charts/pie_and_donut_labels.html#sphx-glr-gallery-pie-and-polar-charts-pie-and-donut-labels-py

https://matplotlib.org/3.1.3/tutorials/introductory/sample_plots.html

https://matplotlib.org/3.1.1/gallery/index.html

https://newville.github.io/wxmplot/overview.html

https://stackoverflow.com/questions/19898115/wxpython-with-matplotlib

https://stackoverflow.com/questions/18769870/matplotlib-wxpython-not-sizing-correctly-with-legend

https://discourse.matplotlib.org/t/a-wxpython-matplotlib-basemap-example/10220/10

https://wiki.wxpython.org/MatplotlibEquationEditor

https://wiki.wxpython.org/MatplotlibFourierDemo

https://intellipaat.com/blog/tutorial/python-tutorial/python-matplotlib/

http://www.python-simple.com/python-matplotlib/pie.php

https://umar-yusuf.blogspot.com/2016/08/embedding-matplotlib-figure-in-wxpython.html

- - - - -

https://wiki.wxpython.org/TitleIndex

https://docs.wxpython.org/


Thanks to

Hatenadiary (sample_three.py coding), Matplotlib.org, the wxPython community...


About this page

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

30/08/20 - Ecco (Created page for wxPython Phoenix).


Comments

- blah, blah, blah....

How to use Matplotlib - Part 1 (Phoenix) (last edited 2020-10-07 09:50:38 by Ecco)

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