Understanding Matplotlib Drawings

Source: Internet
Author: User

Matplotlib is an open source project based on the Python language, designed to provide Python with a data-drawing package. Matplotlib may be the most widely used package in the field of Python 2d-drawing. It makes it easy for users to graphically visualize data and provide a variety of output formats.

Matplotlib uses NumPy for array operations and calls a series of other Python libraries for hardware interaction. The core of Matplotlib is a set of object-composed drawing APIs.

You need to install Python, numpy and matplotlib. (You can download the Python compiler to python.org.) For the installation of the relevant Python package, see my Python tips)

Matplotlib official website is: http://matplotlib.org/official website has the rich legend and the document explanation.

Matplotlib's address at GitHub is: Https://github.com/matplotlib welcomes interested developers to fork.

Matplotlib is inspired by Matlab to build, imitate Matlab but do not imitate "charge"

11 Simple examples

(1) Drawing, draw a straight line

Import1], [0, 1])      #  plot a line from (0, 0) to (1, 1)plt.title ("a strait Line") Plt.xlabel ("x Value") Plt.ylabel ("  y value") plt.savefig ("demo.jpg") Plt.show ()

(2) Analysis

The above code actually encapsulates a lot, if we want to simply quickly draw, then you simply call the above code. But as a programmer, how can you be willing to be a caller, let's untie Matplotlib's core veil

First line, Plt.plot ([0,1],[0,1]) source code

# source Code 1
defPlot (*args, * *Kwargs): Ax= GCA ()#(1) Get axes #Allow callers to override the passing hold=true| FalseWashold =ax.ishold () hold= Kwargs.pop (' hold', None)ifHold is notNone:ax.hold (Hold)Try: Ret= Ax.plot (*args, **kwargs)#(2) Call Ax.plot ()draw_if_interactive ()finally: Ax.hold (washold)returnRet

We see the inside code (1) called GCA, and when axes is obtained, plot is done through AX, code (2)

OK, then go further AX=GCA (), view the source code of GCA ()

# source Code 2
def GCA (* *Kwargs) :"" " Get the Current:class: ' ~matplotlib.axes.axes ' instance on The current figure matching the given keyword args, or create one. If the current axes doesn ' t exist, or isn ' t a polar one, the appropriate axes would be created and then returned. "" = GCF (). GCA (* * Kwargs) return ax

Well, in fact there are caves, continue to track the source of GCF ()

#源码 3
defGCF ():"Get A reference to the current figure."Figmanager= _pylab_helpers. Gcf.get_active ()#(1) Remove the last one from the active list of the figure and return none if the list is empty ifFigmanager is notNone:returnFigManager.canvas.figure#(2) return directly to the topmost figure in the current active figure list Else: returnFigure ()#(3) If not, create a

Get a figure here, if there are multiple figure in the program, then return to the one that is active (activation means if there are multiple windows, then the topmost one, the window touching the mouse, keyboard input), if not created. When created, this figure is set to the active figure by default.

OK, backtrack to source 2. That is, this GCA () is called Figure GCA (), then continue the journey of exploration.

#Source code 4 Figure class of GCAdefGCA (Self, * *Kwargs):"""Get The current axes, creating one if necessary the following Kwargs is supported for ensuring the RET        Urned axes adheres to the given projection etc., and for axes creation if the active axes does not exist: % (Axes) s"""Ckey, CAx= Self._axstack.current_key_axes ()#(1) The rough axes is stack        #If there exists an axes in the stack see if it maches        #The desired axes configuration        ifCax is  notNone:#If no Kwargs is given just return the current axes            #This was a convenience for GCA () on axes such as polar etc.            if  notKwargs:returnCAx#If the user has specified particular projection detail            #Then build up a key which can represent this            Else:                #we don ' t want to modify the original Kwargs                #So take a copy so the We can do and we like to itKwargs_copy =kwargs.copy () Projection_class, _, Key=process_projection_requirements (self,**kwargs_copy)#Let the returned axes has any gridspec by removing it from                #The keyCkey = ckey[1:] Key= Key[1:]                #if the CAX matches this key then return the axes, otherwise                #continue and a new axes would be created                ifKey = = Ckey andisinstance (CAx, projection_class):returnCAx#no axes found, so create one which spans the figure        returnSelf.add_subplot (1, 1, 1, **kwargs)

This is similar to the above GCF, and also to see if there is an existing axes, if there is a direct call, if it does not exist, it is through Figure.add_subplot (1,1,1) to create a axes.

Well, to this side, we have deep contact with figure,axes by looking at the source code. The actual simple sentence plt.plot () is implemented by axes call plot () on a figure.

So we can write it ourselves.

FIG1 = plt.figure ('fig1'# gets a figure, this figure is the vector of all the next objects that are drawn on this. Can be understood as border fig1_axes_1 = fig1.add_axes ([0.1, 0.1, 0.8, 0.8]) Fig1_axes_1.plot ([0,1],[0,1])

2 Clarify relationship

The following contents are reproduced from http://www.cnblogs.com/vamei/archive/2013/01/30/2879700.html

We changed the line drawing above to object-oriented (OO, object-oriented), so we introduced two classes: Figure and Figurecanvas. (Functional programming also calls these classes, except that the calling procedure is obscured by a function call.) )

#object-oriented Plot fromMatplotlib.figureImport Figure fromMatplotlib.backends.backend_aggImportFigurecanvasagg as Figurecanvasfig=Figure () canvas=Figurecanvas (Fig) Ax= Fig.add_axes ([0.1, 0.1, 0.8, 0.8]) line,= Ax.plot ([0,1], [0,1]) Ax.set_title ("a straight line (OO)") Ax.set_xlabel ("x Value") Ax.set_ylabel ("y value") Canvas.print_figure ('demo.jpg')

In the example above, we have constructed at least four objects: Fig, canvas, ax, line. They belong to the figure class, the Figurecanvas class, the Axes class, and the Line2D class respectively. (Use obj.__class__.__name__ to query the class to which the object belongs)

Before we dive into each object, let's start with a metaphor. Look at one of the following pictures:

As you can see, there is a house with windows and doors on it, stripes on the windows, handles on the door, and a little turtle outside the image. We refer to houses, windows, doors, stripes, handles, all of which can be called objects. There are dependencies between different objects, such as windows and doors belonging to the house, while the handle belongs to the door. The tortoise and the house are two objects in parallel. In addition, there is a box outside the entire image to indicate the scope of the drawing, and all the above mentioned elements are attached to the box.

This is an object-oriented approach to understanding an image. In fact, objects are the most natural way to describe an image, and the most successful area of object-oriented programming is in computer graphics.

Let's first look at what the figure and axes objects are. In Matplotlib, the entire image is a figure object. You can include one or more axes objects in a figure object. Each axes object is a drawing area that has its own coordinate system. The logical relationship is as follows:

Turn your head to see a straight line chart. The entire image is a fig object. There is only one coordinate system area in our drawing, that is ax. In addition, the following objects are available. (the base type of the object is represented in parentheses)

Title is the caption. Axis is the axis and label is the axis label. Tick is the tick mark, and the tick label is the scale comment. Each object has the following object affiliation:

(YAxis also has tick, label and tick label, not drawn)

Although data is a key part of the data drawing, which is the graphical display of the figure itself, it must be combined with Xaxis, YAxis, and title to truly form a plot area axes. There is no point in a simple line that cannot read out the scale. Xaxis, YAxis, and title together form the auxiliary part of the data guide.

The above element also contains multiple graphic elements. For example, our data object is a line (line2d). The title, The Tick label and the label are all text, and the tick is made up of the line 2D and the Tick label, Xaxis by the axis lines and tick and label, ax by Xaxis, YAxis, title, Data, and Ax itself forms part of the fig. Each of the above objects, whether line2d, text or fig, comes from a base class called artist.

The original program for OO drawing also has a canvas object. It represents the back end (backend) that actually makes the drawing. Artist is just a drawing on the logic of the program, it must be connected to the back-end drawing program to actually draw it on the screen (or save it as a file). We can understand canvas as the physical (or hardware) implementation of the drawing.

In the OO drawing program, we did not actually see the title, tick, tick label, Xaxis, YAxis object, but instead indirectly set these objects using the Ax.set_* method. But these objects are real, and you can find their "true flesh" from the upper objects. For example, Fig.axes[0].xaxis is the Xaxis object on our way above. We can find it in the order of Xaxis---axes[0] (that is, ax). So, repeating what we have just said, a fig is a complete image. For each object of the artist class, there is a findobj () method to display all the underlying objects that the object contains.

Coordinate

Coordinates are the basis of computer graphics. The computer screen is made up of pixel dots. To display an image on the screen, the computer must tell the screen what to display at each pixel point. Therefore, the coordinate system closest to the hardware is the coordinate system in pixels. We can indicate a point on the display by specifying the pixel location. This is called the display coordinate (displayed coordinate), in pixels.

However, pixel coordinates are not easily incorporated into the drawing logic. The same program, on different monitors to adjust the pixel value to ensure that the image is not deformed. So, in general, there will be image coordinates and data coordinates.

Image coordinates treat the lower left corner of a graph as the origin, and the X-direction and y-direction total length of the image as 1. 0.2 in the X-direction refers to the total length of the 20% image in the x direction, and the length of the Y-direction 0.8 to the total Y-direction of 80%. (0.5, 0.5) is the midpoint of the image, (1, 1) refers to the upper-right corner of the image. For example, in the following procedure, when we use Add_axes, the first two elements are the position of the lower left corner of the axes at the image coordinates of FIG, and the last two elements refer to the X-direction and y-direction lengths of the axes in the image coordinates of FIG. The image coordinates of FIG are called figure coordinates and are stored in the Fig.transfigure

(Similarly, each axes, such as AX1, has its own image coordinates.) It takes the total length of the Ax1 drawing area as 1, called the axes coordinate. That's ax1.transaxes. (0.5, 0.5) is represented at the center of the axes. The axes coordinate is similar to the figure coordinate principle, except that the base area used is different. )

 fromMatplotlib.figureImport Figure fromMatplotlib.backends.backend_aggImportFigurecanvasagg as Figurecanvasfig=Figure () canvas=Figurecanvas (Fig)#First axesAX1 = Fig.add_axes ([0.1, 0.1, 0.2, 0.2]) line,= Ax1.plot ([0,1], [0,1]) Ax1.set_title ("Ax1")#Second axesAX2 = Fig.add_axes ([0.4, 0.3, 0.4, 0.5]) SCA= Ax2.scatter ([1,3,5],[2,1,2]) Ax2.set_title ("ax2") Canvas.print_figure ('demo.jpg')

We plotted the lines between two points when plotting, for example, using plot. These two points are (0, 0) and (1, 1) respectively. (The first table in plot is two x-coordinates, and the second table is two y-coordinates). The coordinate system used at this time is the data coordinate system (AX1.TRANSDATA). We can read the location of the data coordinates from the plotted axis.

If you are drawing specific data, then the data coordinates are in line with our needs. If you are drawing additional information such as headings, then the axes coordinates meet our needs. If it is an annotation of the entire image, then the figure coordinates are more in line with requirements. Each artist object has a transform property that is used to query and change the coordinate system used. If the coordinates are displayed, the Transform property is none.

Understanding Matplotlib Drawings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.