Matplotlib module Getting Started tutorial in Python

Source: Internet
Author: User
1 about matplotlib modules

Matplotlib is a Python module developed by John Hunter to draw two-dimensional graphics. It takes advantage of Python's numerical calculation module Numeric and Numarray, cloning many functions in Matlab to help users easily obtain high-quality two-dimensional graphics. Matplotlib can draw various forms of graphics including ordinary line graph, histogram, pie chart, scatter plot and error line graph, etc., can be more convenient to customize the various properties of the graph than the line type, color, thickness, font size, etc. it is well supported by some TeX typesetting commands, You can display the mathematical formula in the graph in a more beautiful way. Matplotlib is also easy to master, because most of the functions used by Matplotlib are the same as the corresponding functions in Matlab, and the meaning of various parameters, using the same method, which makes the user familiar with Matlab feel handy. For those unfamiliar with Matlab, the meaning of these functions is often at a glance, so as long as it takes a little time to grasp.

Matplotlib currently contains 37 different modules, such as MATLAB, Mathtext, finance, dates

And so on, one of the most direct relations with drawing is the MATLAB module. You can load and view the functions it provides with the following command

>>> Import matplotlib.matlab>>> dir (Matplotlib.matlab)

If you want to understand how a function in a module is used, you can use the Help command. As the following command

>>> Help (Legend) >>> Help (plot)

Returns information about the two functions, legend and plot.

In this paper, some examples are proposed to illustrate the main characteristics of matplotlib. I believe that by reading these examples, you can have a basic understanding of the use of matplotlib.

2 drawing a set of power functions

Let's start with a simple example. Suppose you want to display a set of power functions in a graph. The base of this set of power functions is different, 10, natural logarithm E and 2. You can use the following Python script to depict this set of curves, as shown in Figure 1.

  From Matplotlib.matlab import *   x = Linspace ( -4, 4, 2)  f1 = Power (x)  F2 = Power (e, x)  F3 = Power (, x)   plot (x, F1, ' R ', x, F2, ' B ', X, F3, ' G ', linewidth=2)  axis ([ -4, 4, -0.5, 8]) text (1, 7.5, R ' $10^x$ ', fontsize=1 6) Text (2.2, 7.5, R ' $e ^x$ ', fontsize=16) text (3.2, 7.5, R ' $2^x$ ', fonsize=16) title (' A Simple example ', fontsize=16)  s Avefig (' Power.png ', dpi=75) show ()

Figure 1: A set of power functions

The first line of the program loads the MATLAB module. The next few lines of statements (up to savefig) seem to be running the MATLAB program, because Linspace, power, Plot,axis, text, title These functions also exist in MATLAB. This example shows some of the more commonly used drawing functions in matplotlib, such as Plot,axis,title. Plot is a very powerful function, by changing its parameter options, you can flexibly modify the various properties of the graph, such as the choice of line, color, width and so on.

Display mathematical formulas in a drawing

Matplotlib can support a portion of Tex's typesetting instructions, so users will feel very handy when drawing graphs containing mathematical formulas and can get a more satisfying display, all they need is some Tex typesetting knowledge. The following example shows how to display mathematical formulas in different positions of the graph, such as the axis labels, the caption of the graphic, and the appropriate position in the drawing. The corresponding Python program is as follows, and the resulting graph is shown in Figure 2.

From Matplotlib.matlab Import *
def f (x, C):
M1 = sin (2*pi*x)
M2 = exp (-c*x)
Return multiply (m1, M2)
x = Linspace (0, 4, 100)
Sigma = 0.5
Plot (x, f (x, sigma), ' R ', linewidth=2)
Xlabel (R ' $\rm{time} \ t$ ', fontsize=16)
Ylabel (R ' $\rm{amplitude} \ f (x) $ ', fontsize=16)
Title (R ' $f (x) \ \rm{is \ damping \ with} \ x$ ', fontsize=16)
Text (2.0, 0.5, R ' $f (x) = \rm{sin} (2 \pi x^2) e^{\sigma x}$ ', fontsize=20)
Savefig (' Latex.png ', dpi=75)
Show ()

Figure 2: Display of mathematical formulas in graphs

It can be seen from the program that the typesetting of mathematical formulae in matplotlib is very simple. As with Tex typographic conventions, the formula part to be inserted is identified by a pair of dollar sign $, and the specific layout command is the same as Tex. You can insert the desired formula in any place where the text can be displayed, such as the label of the axis, the title, and so on. It is important to note that the string where the mathematical formula is located has a tag R at the beginning, indicating that the string is a raw string. This is because when the formula is written, the string contains content that must be parsed according to TeX's specifications, not other specifications. So using raw string prevents other rules from interpreting the ambiguity of certain special characters in the string. As you can see from the generated graph, the effect of the formula display is more beautiful.

3 drawing graphics in other formats

In addition to the usual line graphs, matplotlib can also draw other kinds of graphs, such as histograms, pie charts, error bars, and so on. Here is an example of working with experimental data. It compares the actual measured current with the theoretical calculation current in the form of histogram, and also shows the error distribution of the measurement. The program first reads the experimental data Current.dat, obtains the data and uses the function bar to draw.

From matplotlib.matlab import * filename = "D:\\wei\\exp\\current.dat" X = load (filename) DP = x[:, 0]i_mea = x[:, 1]i_mea_e rr = x[:, 2]i_cal = x[:, 3]i_cal_err = x[:, 4]width = 3H1 = Bar (DP, I_mea, width, color= ' R ', yerr=i_mea_err) H2 = Bar (dp+wi DTH, i_cal, width, color= ' B ', Yerr=i_cal_err) xlabel (' particle diameter (nm) ', fontsize=16) xticks (Dp+width, DP) Ylabel (' Signal current (NA) ', fontsize=16) title (' measured-current vs. calculated-current ') Legend ((H1[0], h2[0]), (' measured Current ', ' calculated current '), loc=2) savefig (' Current.png ', dpi=75) show ()

Figure 3: Measuring current vs. Calculating current

As can be seen from the program, the function load greatly facilitates the reading of the data file (no need to write code to process the data file), its output is directly passed to the function bar, and then complete the histogram and error line drawing.

Visualization of 4 GLP set calculation results

Python is a more appropriate scripting language for scientific computing, and its computational power can be further enhanced if the Numeric and Numarray modules are used. Matplotlib also makes full use of these two modules to visualize the results of a high-quality calculation. Here is an example that calculates and displays a collection of two-dimensional, well-checked GLP (good Lattice point set). The GLP set is a set of pseudo-random numbers generated by the algorithm, which is useful in some optimization calculations, and can be found in the reference literature in detail. The following Python program first defines a function GLP (N1, N2) to produce the required GLP set, and then uses Matplotlib to show its distribution (which should be evenly distributed).

# A, dimensional GLP set # with n1=377, n2=610from matplotlib.matlab import *def GLP (N1, n2): Q = Zeros ((2, N2), Float) H1 = 1; H2 = N1 for I in Arange (n2-1): q[0][i] = (Fmod (h1* (i+1), N2) -0.5)/n2 q[1][i] = (Fmod (h2* (i+1), N2) -0.5)/n2 q[0][n2-1] = (n2-0.5)/n2 q[1][n2-1] = (n2-0.5)/n2 return qn1 = 377;  N2 = 610q = GLP (n1, n2) x = q[0,:]y = q[1,:]plot (x, Y, ' R. ', linewidth=2) axis ([0, 1, 0, 1]) title (R ' $\RM{GLP \ Set \ with} \ n_1 = 377, \ n_2 = 610$ ') savefig (' glp.png ', dpi =) Show ()

Figure 4:GLP Distribution of a collection

At first we used Matlab to do this work, and now it is as simple as Python to implement it. The implementation of the function GLP in the program is mainly based on the fast Numeric, and the calculated results are displayed directly with the plot function, which is very convenient. This example, which includes the previous example, shows that matplotlib can often perform the visualization of computational results in a concise and efficient manner when using Python for certain scientific and engineering calculations.

5 mode of operation and output modes of graphs

At last, we briefly introduce the working mode of matplotlib and the way of outputting graphics. Matplotlib has two modes of operation: Interactive mode (interactive mode) and batch mode. It is easy to understand the differences between the two modes. The first pattern is the command to run the drawing one at a prompt of a Python Shell.

The second mode is to write the drawing command as a script file and execute the file in the appropriate environment. The output of the final graph also has two ways, that is, the GUI output mode and non-GUI output mode. Simply put, the output of GUI mode is to display the generated graphics directly on the screen, while the output of non-GUI mode is to save the graphics in some format file, such as the ps,png format. Either way is related to the backend used by the system (backend can be understood as the back-end drawing engine). The backend related to GUI mode output include WxPython, Tkagg, Tkinter and so on. and non-GUI-related backend including GD, Ps,paint and so on. Summarizes the main backend supported by matplotlib at present.
Figure 5:matplotlib supports the main backend

Users can choose one of the output methods according to their actual needs, of course, can also be used in two ways. Some of the above examples are used in both ways. The last line of the above Python script Show is responsible for displaying the graphic on the screen, and the command Savefig will save the graphic to the appropriate format of the file, the default output format is the PNG format.

6 Summary

As an ongoing project, Matplotlib leverages Python's Numeric (Numarray) module to provide a solution for visualizing data using Python, further enhancing Python's ability to perform scientific calculations. Matplotlib is easy to learn, it clones many functions in MATLAB, which will benefit users who understand MATLAB. Other features include the ability to draw multiple types of graphics, easily and flexibly modify the various properties of the graph, and to display the mathematical formulas in the graph in a more aesthetically pleasing manner. One of the attractions of Gnuplot,matplotlib, as compared to some other drawing programs, is the high quality of the output graphics. The disadvantage is that the function of matplotlib is not perfect at present, such as the current can not support three-dimensional drawing, TeX typesetting support is not enough and so on. However, given that it is an ongoing project, these should not be demand perfection. In general, if you need a visual tool and want it to have high-quality output, then Python's matplotlib module should be an option worth considering.

  • 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.