Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the core of matplotlib?

2025-03-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you what is the core of matplotlib, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

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 drawing API composed of objects.

The matplotlib project is initiated by John D. Hunter. John D. Hunter died last year of cancer, but his unparalleled contribution to the community will last forever.

John D. Hunter

You need to install Python, numpy and matplotlib. (you can download the Python compiler at python.org. For the installation of Python packages, please see my Python Tips)

The official website of matplotlib is: the official website of http://matplotlib.org/ has rich illustrations and documentation.

The address of matplotlib in github is: https://github.com/matplotlib Welcome interested developers fork.

Functional drawing

Matplotlib is inspired by MATLAB. MATLAB is a widely used language and tool in the field of data drawing. The MATLAB language is process-oriented. With the function call, MATLAB can easily use one command to draw a straight line, and then use a series of functions to adjust the results.

Matplotlib has a set of drawing interfaces that completely imitate the functional form of MATLAB, in the matplotlib.pyplot module. This set of function interfaces makes it easy for MATLAB users to transition to matplotlib packages. Next, we call the module to draw a straight line.

# a strait line: use pyplot functionsfrom matplotlib.pyplot import * plot ([0,1], [0,1]) # plot a line from (0,0) to (1,1) title ("a strait line") xlabel ("x value") ylabel ("y value") savefig ("demo.jpg")

Each of the above commands is simple, and you can read out what the function is going to do from the function name. For example, plot draws lines and title adds headings. The final saved demo.jpg is as follows:

The above function call is very convenient. In Python special methods and multiple paradigms, we have mentioned that functional programming in Python is achieved by encapsulating objects. The same is true of functional calls in matplotlib. Matplotlib essentially builds objects to build images. Functional programming encapsulates the process of building an object in a function, which makes it convenient for us.

In matplotlib.pyplot, you can also find the following drawing function. If you often use data graphics programs, you should be familiar with these graphics:

The drawing program is as follows:

View Code

The marvin.jpg used above is the following picture, please save it to your local computer:

Functional programming creates a working environment for simulating MATLAB, and there are many shaped drawing functions. If only as a general user of Matplotlib (not a developer), pyplot can meet most of the needs.

(of course, matplotlib is free and open source, and MATLAB is expensive and closed. This is the place where there is no "simulation")

Object oriented programming

Although functional drawing is convenient, using functional programming has the following disadvantages:

1) A layer of "function" calls is added, which reduces the efficiency.

2) the membership relationship is covered up by the function. The entire matplotlib package is made up of a series of organized and subordinate objects. The function masks the original membership and complicates things.

3) the details are masked by the function. Pyplot can not completely copy all the functions of the object system, and many details of the image will eventually return to the object.

4) everything can be done in at least two ways, and users are easily confused.

For developers, knowing the object is the first step in participating in a Matplotlib project.

We changed the above line drawing to object-oriented (OO, object-oriented), for which we introduced two classes: Figure and FigureCanvas. (functional programming also calls these classes, but the calling procedure is obscured by function calls.)

# object-oriented plotfrom matplotlib.figure import Figurefrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvasfig = Figure () canvas = FigureCanvas (fig) ax = fig.add_axes ([0.1,0.1,0.8,0.8]) line, = ax.plot ([0L1], [0L1]) ax.set_title ("a straight line (OO)") ax.set_xlabel ("x value") ax.set_ylabel ("y value") canvas.print_figure ('demo.jpg')

The new demo.jpg is as follows:

Understand the object

In the above example, we have built at least four objects: fig, canvas, ax, and line. They belong to the Figure class, FigureCanvas class, Axes class and Line2D class, respectively. (use obj.__class__.__name__ to query the class to which the object belongs)

Before we delve into each object, let's make a metaphor. Look at the following picture:

This picture is drawn with KTurtle. See build your child into a programmer

You can see that there is a house in the picture with windows and doors, stripes on the windows, handles on the doors, and a little turtle outside the image. The houses, windows, doors, stripes and handles we mentioned can all be called objects. There are dependencies between different objects, such as windows and doors belong to the house, while handles belong to the door. The turtle and the house are two parallel objects. In addition, there is a box outside the entire image to indicate the extent to which you can draw, and all the elements mentioned above are attached to the box.

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

Let's first look at what 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 with its own coordinate system. The logical relationship is as follows:

Turn around and look at the line chart. The entire image is a fig object. There is only one coordinate system area in our drawing, that is, ax. In addition, there are the following objects. (the basic type of object is indicated in parentheses)

Title is the title. Axis is the axis and Label is the axis. Tick is the tick mark and Tick Label is the tick mark. There are the following object affiliation relationships between objects:

(yaxis also has tick, label and tick label, but not painted)

Although data is the key part of data drawing, that is, the graphical display of the data itself, it must be together with xaxis, yaxis and title to really form a drawing area axes. A simple, unreadable scale line is meaningless. Xaxis, yaxis, and title combine to form an auxiliary part of the data (data guide).

The above elements also contain a variety of graphic elements. For example, our data object is a Line2D. Title, tick label and label are all text (Text), while tick is composed of short-term (Line 2D) and tick label, xaxis is composed of axis lines, tick and label, ax is composed of xaxis, yaxis, title and data, and ax itself constitutes a part of fig. Each of the above objects, whether Line2D, Text, or fig, comes from a base class called Artist.

The original program of OO drawing also has a canvas object. It represents the backend that actually does the drawing. Artist is just a drawing in the logic of the program. It must be connected to a back-end drawing program before it can be really drawn on the screen (or saved as a file). We can think of canvas as a physical (or hardware) implementation of drawing.

In the OO drawing program, we don't really see the title, tick, tick label, xaxis, yaxis objects, but use the ax.set_* method to set these objects indirectly. But these objects are real, and you can find their "real bodies" in the upper objects. For example, fig.axes [0] .xaxis is the xaxis object on our way above. We can find it in the order fig-> axes [0] (that is, ax)-> xaxis. So, to repeat what we have just said, a fig constitutes a complete image. For each object of the Artist class, there is a findobj () method to display all the lower-level objects contained in that object.

Coordinate

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

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

The image coordinates regard the lower left corner of a picture as the origin, and the total length of the x direction and y direction of the image as 1. 0.2 in the x direction refers to the total length of 20% of the images in the x direction, and 0.8 in the y direction refers to 80% of the total length in the y direction. (0.5, 0.5) is the midpoint of the image, and (1, 1) refers to the upper right corner of the image. For example, in the following program, when we use add_axes, among the parameters passed, the first two elements are the position of the lower left corner of axes in the image coordinates of fig, and the last two elements refer to the length of axes in the x direction and y direction of the image coordinates of fig. The image coordinates of fig are called Figure coordinates and are stored as 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, which is called Axes coordinates. Also known as ax1.transAxes. (0.5,0.5) is in the center of the Axes. The principle of Axes coordinates is similar to that of Figure coordinates, except that the base area used is different.)

# object-oriented plotfrom matplotlib.figure import Figurefrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvasfig = Figure () canvas = FigureCanvas (fig) # first axesax1 = fig.add_axes ([0.1,0.1,0.2,0.2]) line, = ax1.plot ([0L1], [0L1]) ax1.set_title ("ax1") # second axesax2 = fig.add_axes ([0.4,0.3,0.4,0.5]) sca = ax2.scatter Ax2.set_title ("ax2") canvas.print_figure ('demo.jpg')

We draw the line between two points when drawing, for example, when using plot. These two points are (0,0) and (1,1), respectively. The first table in plot has two x coordinates and the second table has two y coordinates. The coordinate system used here is the data coordinate system (ax1.transData). We can read out the location of the data coordinates through the drawn axes.

If you are drawing specific data, then the data coordinates meet our needs. If you are drawing additional information such as the title, then the Axes coordinates meet our requirements. If it is the annotation of the whole image, then the Figure coordinates are more in line with the 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.

Go deep into the foundation

In the above example, whether you use plot to draw lines or scatter to draw scatters, they are still relatively mature functions. Matplotlib actually provides more freedom, allowing users to draw graphics in a more basic way, such as below, we draw a Pentagon.

# object-oriented plotfrom matplotlib.figure import Figurefrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvasfig = Figure () canvas = FigureCanvas (fig) ax = fig.add_axes ([0.1,0.1,0.8,0.8]) from matplotlib.path import Pathimport matplotlib.patches as patchesverts = [(0.1,0.1,0.8,0.8), (0.5,1.5), (1.1,1.), (1.,0.), (0. 0.),] codes = [Path.MOVETO, Path.LINETO, Path.CLOSEPOLY,] path = Path (verts, codes) patch = patches.PathPatch (path, facecolor='coral') ax.add_patch (patch) ax.set_xlim (- 0.5) ax.set_ylim (- 0.5) canvas.print_figure ('demo.jpg')

In the above program. We first determine the vertices, and then build a path object, which is actually a line of five vertices. In codes, we first use MOVETO to move the brush to the starting point, and then connect it with a straight line (LINETO). (we can also connect lines with curves, such as CURVE4, but we don't use it here). After path established the closed pentagon, we constructed the patch object on the basis of path, which is a graphic block. The background color of patch is selected as coral. Finally, we add this patch object to the pre-prepared ax to complete the entire drawing.

In the above process, we are like a child with a paintbrush, drawing the picture in mind step by step. This is a deep understanding of the charm of matplotlib-creating your own data drawing function!

Encapsulate the above program into a function and retain vertices and other parameter interfaces to form a Pentagon drawing function. O (∩ _ ∩) O~ We have also created a new "one-click drawing")

You can imagine how a plot function is implemented with a path object.

The above is all the content of this article "what is the Core of matplotlib?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report