Explain the Core Principles of Matplotlib

Source: Internet
Author: User
Keywords matplotlib matplotlib tutorial matplotlib python
Matplotlib is an open source project based on the Python language, which aims to provide a data plotting package for Python.

I believe everyone has used it to visualize data. I have also shared 25 Python codes of commonly used Matplotlib diagrams before.

But have you understood the core principle of its drawing?

Then why not take a look at this article by classmate Huang!

Core principles explained

The principle of using matplotlib drawing is mainly to understand the relationship between figure (canvas), axes (coordinate system) and axis (coordinate axis).


Take "Academics student Zhang San sketching and painting" as an example to illustrate the relationship between the three.

Zhang San's artboard


First of all, if Zhang San wants to draw, does he need to prepare a canvas on the drawing board? Comparing to matplotlib, it is equivalent to initializing a figure (canvas). Any graphics we draw are operated on this figure (canvas).

Next, Zhang San needs to allocate different areas to the figure (canvas) and specify which piece should be painted. Comparing to matplotlib, it is necessary to specify axes (coordinate system), each axis (coordinate system) is equivalent to an area on a canvas. On a canvas, you can assign different areas, that is, on a canvas, you can specify multiple axes (coordinate systems).

Finally, Zhang San draws graphics on the allocated different areas. On a canvas, the most drawn should be a 2D image, or a 3D image, as shown in the picture, Zhang San painted in the area A puppy drew a kitten in area two and a bald head in area three. Comparing to matplotlib, we draw a bar chart in axes1, a pie chart in axes2, and a line chart in axes3. When it is a 2D graph, there will be an X axis and a Y axis; when it is a 3D graph, there will be an X axis, a Y axis and a Z axis, this axis is what we call the "coordinate axis".

matplotlib drawing


Through the above analysis, it is summarized as follows: on a figure (canvas), there can be multiple areas axes (coordinate system), we draw on each coordinate system, that is to say, each axis (coordinate system), there is an axis (Axis).

Special note: in matplotlib, figure canvas and axes axes can not be displayed. What we can see is various graphs of axis axes.

Installation and import of matplotlib library

1) Installation

pip install matplotlib

2) Import related libraries

Now you don't need to pay attention to what the following code means, just have a subjective impression. In a future article, I will introduce to you which parameters you do not understand.

import numpy as npimport pandas as pdimport matplotlib as mplimport matplotlib.pyplot as plt# exclude warning information import warningswarnings.filterwarnings("ignore")# print version information display(np.__version__)display(pd.__version__)display(mpl.__version__) # matplotlib Drawing common parameter settings mpl.rcParams["font.family"] = "SimHei" # Set font mpl.rcParams["axes.unicode_minus"]=False # Used to display negative signs normally plt.rcParams['font.sans -serif']=['SimHei'] # Used to display Chinese tags normally # Embedded display graphics %matplotlib inline

The results are as follows:


Two ways to create a figure (canvas)

1) Draw a simple line chart

import matplotlib as mplimport matplotlib.pyplot as pltx = [1,3,5,7]y = [4,9,6,8]plt.plot(x,y)plt.show()

In the previous narrative, we have already said that if you want to use matplotlib for drawing, you must first create a figure (canvas) object, and then have axes (coordinate system). But observing the above code, we have not created a figure object, so how can we draw a picture?

For the above questions, next we will talk about two ways to create a figure (canvas).

2) Two ways to create a figure (canvas)

* Implicit creation * display creation

① Create a figure object implicitly

When the plt.xxx() drawing code is executed for the first time, the system will determine whether there is already a figure object. If not, the system will automatically create a figure object, and on top of this figure, it will automatically create an axes coordinate system ( Note: a figure object is created by default, an axes coordinate system).

In other words, if we don't set the figure object, there can only be one axes coordinate system on a figure object, that is, we can only draw one figure.

② Problems with implicit creation of figure objects

Advantages: If you are only drawing a small figure, then directly using plt.xxx() will automatically help us create a figure object and an axes coordinate system. This figure is ultimately drawn on the axes coordinate system.

Disadvantages: If we want to draw multiple graphics on a figure object, then we must get each axes object, and then call the axes object at each position, you can be on the coordinate system of each corresponding position , To draw, as shown below. Note: If the figure object is created by default, then we cannot get the axes object at all. Therefore, we need to show the creation of figure objects.


③ Display and create figure objects: future articles will detail the layout settings

# Manually create a figure object figure = plt.figure() # Get the axes object at each position axes1 = figure.add_subplot(2,1,1)axes2 = figure.add_subplot(2,1,1)


for example:

figure = plt.figure()axes1 = figure.add_subplot(2,1,1)axes2 = figure.add_subplot(2,1,1)axes1.plot([1,3,5,7],[4,9, 6,8])axes2.plot([1,2,4,5],[8,4,6,2]) figure.show()



Complete drawing steps

① Library

import matplotlib as mplimport matplotlib.pyplot as plt

② Create figure canvas object

If you draw a simple small figure, we can not set the figure object, use the figure object created by default, of course, we can also display the figure object created. If a figure canvas, you need to draw multiple graphics. Then you must display and create the figure object, and then get the axes object at each position to draw the graphics at the corresponding position.

③ Layout setting according to figure object

1*11*22*12*2...

④ Get the axes coordinate system object of the corresponding position

figure = plt.figure()axes1 = figure.add_subplot(2,1,1)axes2 = figure.add_subplot(2,1,1)

⑤ Call the axes object to draw graphics at the corresponding position

This step is a step for us to transfer data and draw. For some detailed settings of the graphics, all can be done in this step.

⑥ Display graphics

If plt.show() or figure.show() is drawn in pycharm, this code must be added to display. If you draw in the notebook, you can display it automatically without adding this sentence.

Drawing skills (detail settings)

After understanding the principles of matplotlib drawing, we need to learn the common matplotlib drawing techniques.

* figure canvas * axes coordinate system, there can be multiple coordinate systems on one canvas * axis coordinate axis, there can be multiple coordinate axes in one coordinate system, generally two-dimensional plane coordinate system, or three-dimensional coordinate system * title * legend legend* grid background grid* tick scale* axis label axis name* tick label scale name* major tick label major tick label* minor tick label minor tick label* line line* style line style* marker point marker* font font Related

Common drawing techniques are shown above. These drawing techniques can help us draw more beautiful and intuitive graphics.
Related Article

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.