Matplotlib module Introductory Tutorial in Python _python

Source: Internet
Author: User
Tags numeric natural logarithm sin python script in python

1 About Matplotlib Modules

Matplotlib is a Python module developed by John Hunter to draw two-dimensional graphics. It utilizes the numerical computing module Numeric and Numarray under Python to clone many functions in Matlab to help users get high-quality two-dimensional graphics easily. Matplotlib can draw multiple forms of graphics including ordinary line graphs, histograms, pie charts, scatter plots and error line graphs; it is convenient to customize the various properties of graphics such as the type of graph line, color, thickness, font size, etc. it can well support a part of the TeX typesetting command, You can display the mathematical formulas in the graph in a more beautiful way. Matplotlib Master also very easy, because most of the functions used in matplotlib with the corresponding function in Matlab, and the meaning of various parameters, the use of the same method, which makes the user familiar with the Matlab feel handy. For those unfamiliar with the Matlab users, the meaning of these functions are often at a glance, so long as it takes a little time to master.

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

And so on, the most direct relationship with the drawing is the MATLAB module. You can load and view the functions that it provides by using 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 for both the legend and plot functions.

Some examples are presented to illustrate these main characteristics of matplotlib. I believe that by reading these examples, you can have a basic understanding of the use of matplotlib.

2 draw 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 groups of power functions are 10, and the natural logarithm E and 2 are respectively. You can use the following Python script to paint this set of curves, and the resulting graphs are shown in Figure 1.

  From Matplotlib.matlab import * 
 
 x = Linspace ( -4, 4) 
 f1 = Power (x) F2 = Power ( 
 e, x) 
 F3 = Power (2, 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$ ', Fontsi ze=16)
 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)
 
 savefig (' power.png ', dpi=75) show
 ()

Figure 1: A set of power functions

The first line of the program loaded the MATLAB module. The next few lines (until Savefig) seem to be running the MATLAB program, because Linspace, power, Plot,axis, text, title these functions in the MATLAB also exist. This example shows the use of several 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 graphics of various properties, such as the choice of line style, color, width and so on.

Show the mathematical formula in the graph

Matplotlib can support some of the layout instructions in Tex, so the user will be very handy when drawing graphs with mathematical formulas and can get a more satisfying display, all it takes is some Tex typesetting knowledge. The following example shows how to display mathematical formulas in different positions of the graphic, such as the axis labels, the title of the graphic, and the appropriate position in the graphic. 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

As can be seen from the program, it is easy to make a composition about mathematical formulas in matplotlib. As with the agreement in Tex typesetting, the portion of the formula to be inserted is identified by a pair of dollar sign $, and the specific typographic order is the same as Tex. You can insert the formula you want in any place where you can display text (such as the label of an axis, the title, and so on). It should be noted that the string at the beginning of the mathematical formula has a tag r that indicates that the string is a raw string. This is because when the layout formula, the contents of the string must be parsed according to the TeX specification, not the other specifications. So using raw string prevents other rules from interpreting the ambiguity of some special characters in the string. From the generated graphics, you can see that the formula shows the effect is more beautiful.

3 Drawing in other formats

In addition to the commonly used line charts, Matplotlib can also draw other kinds of graphics, such as histograms, pie charts, error bars, and so on. The following is an example of processing experimental data. It compares the actual measuring current and the theoretical calculation current with 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_err = x[:, 2]
i_cal = x[:, 3]
i_cal_err = x[:, 4]
width = 3
h1 = Bar (DP, I_mea, W Idth, color= ' R ', yerr=i_mea_err)
h2 = Bar (Dp+width, 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 the code to process the data file), its output is directly passed to the function bar, and then complete the histogram and error line drawing.

4 Visualization of the results of GLP set calculation

Python is a more suitable scripting language for scientific computing, and its computational power can be further enhanced if the Numeric and Numarray modules are used. Matplotlib has also made full use of these two modules, which can achieve the visualization of the results of the calculation with high quality. The following is an example of a set of two d good lattice points GLP (good lattice point set) that is computed and displayed. The GLP set is a set of pseudo random numbers produced by algorithms, which is useful in some optimization calculations, and can be found in the references 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 Two dimensional GLP set 
# with n1=377, n2=610 from
matplotlib.matlab import *
def GLP (N1, n2):
 q = Zer Os ((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
 q
n1 = 377; N2 = 610
q = 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
()

Graph 4:GLP the distribution of sets

Originally we use Matlab to complete this work, now use Python to achieve the same very concise. The realization of function GLP in program is mainly to use the model Numeric, and the calculated results are shown directly by the plot function, which is very convenient. This example (including the previous example) shows that when using Python for some scientific and engineering calculations, Matplotlib is often able to perform the visualization of the results of the calculation with simplicity and efficiency.

5 mode of operation and graphics output mode

Finally, briefly introduce the working mode of matplotlib and the way of output graphics. Matplotlib has two modes of operation: Interactive mode (interactive mode) and batch mode (batch mode). It is easy to understand the difference between the two modes. The first pattern is the command to run the drawing individually under the prompts of a Python Shell.

The second pattern is to write the drawing command in a script file and then execute the file in the appropriate environment. The output of the final graph also has two kinds of ways, namely GUI output mode and non GUI output way. Simply put, the output of the GUI way is to display the resulting graph directly on the screen, but the output of the non GUI mode is to save the graphic as a file in a certain format, such as a file in ps,png format. Either way is related to the backend used by the system (backend can be understood as the drawing engine at the back end). The backend related to GUI mode output include WxPython, Tkagg, Tkinter, etc. The backend related to the non-GUI mode include GD, Ps,paint, etc. The following figure summarizes the main backend currently supported by Matplotlib.
Figure 5:matplotlib Support for the main backend

Users can choose some kind of output according to their actual needs, of course, can also be used in two ways. The above examples are used in both ways. The last line of the above Python scripts shows that the graphic is displayed on the screen, while command Savefig saves the graphic as a file in the format, and the default output format is the PNG format.

6 Summary

As an ongoing project, Matplotlib takes full advantage of the Numeric (numarray) module under Python, providing a solution that uses Python for data visualization, further enhancing the ability of Python to perform scientific calculations. Matplotlib simple and easy to learn, it cloned a number of MATLAB functions, which will help users to understand the MATLAB benefit a lot. Other features include the ability to draw various types of graphics, simple and flexible to modify the various properties of the graphic, can be more beautiful to display the mathematical formula in the graph. One of the attractions of Gnuplot,matplotlib, as compared to other drawing programs, is the higher quality of the output graphics. The disadvantage is that the function of matplotlib is not perfect at present, for example, it can't support three-dimensional drawing at present, the support of TeX typesetting is not enough, etc. But given that it is an ongoing project, these should not be jellyfish. In general, if you need a visual tool and want it to have a high quality output, the Python matplotlib module should be a worthwhile choice to consider.

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.