When viewing Matplotlib official documents and examples, you will find different coding styles and usage patterns. These styles are completely effective, each with its advantages and disadvantages.
Almost all examples can be converted to another style to achieve the same result. Of course, it's important not to confuse your code style.
Two different styles are supported by the official.
The following are the preferred ways to use matplotlib. The preferred Pyplot style, the top import script is usually:
Import As plt Import as NP
Style One: call the drawing function directly , here is a simple example:
Import As plt Import As NP
= Np.arange (0, ten, 0.2= np.sin (x)
Plt.plot (x, y) plt.show ()
Note: This example uses the Pyplot state machine to automatically and implicitly create a graph figure and a coordinate system axes.
Style Two: to fully control your graphics , and more advanced usage, you need to explicitly create graphical figures using the Pyplot interface, and then use the object method:
Import As plt Import as = Np.arange (0, ten, 0.2= np.sin (x)
== Fig.add_subplot (111) Ax.plot (x, y) plt.show ()
style Three: examples of pure matlab style:
from Import *= arange (0, 0.2= sin (x) plot (x, y) show ()
Note: Pylab has integrated the matplotlib,numpy,scipy!
Now look at the more extreme manifestations of style two .
To do this, we introduce two classes: Figure and Figurecanvas. (Automatic, implicit introduction if not explicitly introduced )
fromMatplotlib.figureImport Figure fromMatplotlib.backends.backend_aggImportFigurecanvasagg as FigurecanvasImportNumPy as Npx= Np.arange (0, 10, 0.1) y=np.sin (x) FIG=Figure () canvas=Figurecanvas (Fig) Ax= Fig.add_axes ([0.1, 0.1, 0.8, 0.8]) line,=ax.plot (x, y) ax.set_title ("a straight line (OO)") Ax.set_xlabel ("x Value") Ax.set_ylabel ("y value") Canvas.print_figure ('demo.jpg')
Note: In general, this explicit introduction is likely to bind Matplotlib to a GUI such as Tkinter,pyqt,wxpython
Matplotlib Code Style