Introduction to the basic operating methods of the Python drawing library

Source: Internet
Author: User
This article mainly introduces the use of Numpy+matplotlib drawing of the basic operation, the article introduced in very detailed, for everyone to learn matplotlib drawing has a certain reference learning value, the need for friends below to learn together.

Briefly

Matplotlib is a python-based 2D drawing library that makes it easy to draw line charts, histograms, power spectra, scatter plots and other commonly used charts in a Python script, with simple syntax. Specific introduction See Matplot official website.

Numpy (Numeric python) is an extension of the Python numeric operations that mimics MATLAB, providing many advanced numerical programming tools such as matrix data types, vector processing, and sophisticated operations libraries. is designed for rigorous digital processing, and it is said that since his appearance, NASA has many of the original Fortran and MATLAB work to the numpy to do, visible its strong ... His official website is here, the specific information is inside.

Installation

$sudo apt-get Install python-matplotlib$sudo apt-get Install Python-numpy

(Niuli Dafa Good ~)

Use

Matplotlib can be used in scripts, but if used in the Ipython will be more dazzling (directly add –pylab parameters can be exempted from the process of the package), and can be similar to Matlab/mathematica-like functions, instant input, instant output. Personally think that he is imitating matlab/mathematica, but indeed more convenient programming than the former.

In many cases matplot need to cooperate with the NumPy package, about the NumPy package I do not intend to separate, use the time to mention the line. One thing to note is that the NumPy package is typically imported like this:

Import NumPy as NP

will give him an alias called NP, and this is almost a conventional.

Enter help in Python or ipython (* The function you need to find *) (you need to import the next package, of course).

First image

Packages that need to be imported:

Import NumPy as Npfrom pylab import *

Image of the first function

X = Np.linspace (-np.pi, Np.pi, 256,endpoint=true) c,s = Np.cos (x), Np.sin (x) plot (x,c) plot (x,s) show ()

MATLAB Basic students are certainly not unfamiliar ... Yes, the combination of these two modules is almost the same as the use of Matlab no two.

1, first use the np.linspace method to generate an array of x, the array is from $-\pi$ the beginning to a $\pi$ total of 256 elements of the array, the endpoint parameter indicates whether to include the end of the endpoint (his value is true or FALSE, the first letter to uppercase .... )。 Of course, this array is an ordinary array, no different from the other arrays.

2, then use np.cos() and np.sin() method action on the X array, for each element in the X is calculated, resulting in an array of results. (eliminates the iterative process).

3, then call Pylab's plot method, the first parameter is a horizontal array, the second parameter is an ordinate array, other parameters aside. This way, he will generate a default chart. (not immediately shown)

4, of course, and finally call the Show method to display the chart.

5. Results:

The name of the chart is called Figure1, the left below a few buttons, are very useful things, the lower right corner will show the current mouse left, also very convenient.

Chart layout and coordinate distribution

Each chart is in a figure, and we can generate an empty graph with the following command:

Figure (Figsize= (8,6), dpi=80)

The order of the parameters here is not required, but be sure to add the parameter name, because he distinguishes each parameter according to the parameter name, which is a function different from the C language type. The Figsize parameter represents the width-to-height ratio of a figure, and then the DPI represents the length of each part, such as this means that the image is 640x480.

A window appears immediately after the output command, and all of the plot commands appear immediately on this window without having to enter the show command.

A figure can also display multiple charts, and we can use the following function to split a graph:

Subplot (3,4,6)

This will divide the current figure into 3 rows and 4 columns, and activate the 6th one, the 2nd row 3rd. Future plot is generated on this sub-table, and if you need to replace it, you can re-enter the subplot command to determine its new location.

In addition, if we are not satisfied with the range shown in the chart, we can also directly adjust the chart's coordinate range:

Xlim ( -4.0,4.0) Ylim ( -1.0,1.0)

This means that the range of the x-axis is set at-4 to the range of the 4,y axis set at-1 to 1. Of course, if you want to make a relative change we can take advantage of the Min and Max methods of the next NumPy array. Like X.min() something like that.

If we are not satisfied with the density of the coordinate display, we can also adjust his labeling point:

Xticks (Np.linspace ( -4,4,9,endpoint=true)) Yticks (Np.linspace ( -1,1,5,endpoint=true))

For Xticks and yticks, we can actually pass in any array, which is just a quick-to-generate arithmetic progression for convenience numpy.

Of course, we can also give the label point arbitrary name, like this:

Xticks ([1,2,3,4,5],[' One ', ' both ', ' three ', ' four ', ' five '])

The effect is also very good to imagine, do not map. It is important to note that Latex syntax can also be supported here, and the latex can be referenced between two $. (about Latex)

Here's a little trick, too, that if you want to not display the callout, we can assign an empty array to xticks directly.

Change color and line width

We can use the following methods to specify his color and line width when drawing plot:

Plot (X, C, color= ' #cadae3 ', linestyle= '-', linewidth=1.3, marker= ' o ', markerfacecolor= ' Blue ', markersize=12,)

Again, the order of the arguments here is unimportant, and the name is important.

The color parameter can specify the hue of the RGB, or it can use some default names, such as Red Blue.

The LineStyle parameter specifies the style of the line, referring to the following style:

Parameters style
‘-‘ Solid line
‘–' Dashed
‘-.' Line-point
‘:' Dot Dotted Line

The LineWidth parameter specifies the width of the polyline, which is a floating-point number.

The marker parameter specifies the style of the scatter, referring to the following style:

Parameters style
‘.' Solid Point
' O ' Circle
‘,' A pixel point
' X ' Fork Number
+ Cross
‘*' Asterisk
' ^ ' V ' < ' > ' Triangle (up or down)
' 1 ' 2 ' 3 ' 4 ' Tri-fork (up or down)

Markerfacecolor parameter specifies the color of the marker

The Markersize parameter specifies the size of the marker

This will basically be able to customize any line chart, scatter chart style.

Moving axis

This is a little bit complex, for the time being don't want to know specifically the strange function call, let's record the usage and principle:

Ax = GCA () ax.spines[' right '].set_color (' none ') ax.spines[' top '].set_color (' None ') ax.xaxis.set_ticks_position (' Bottom ') ax.spines[' Bottom '].set_position ((' data ', 0)) ax.yaxis.set_ticks_position (' left ') ax.spines[' left '].set_ Position (' data ', 0)

We know a picture has up and down four axes, here we put the right and the top of the axis color to transparent, and then set the bottom to the y-axis data 0, the left to the x-axis data is 0 of the place. So we can adjust the axis according to where we want to be.

For example, the following official code:

#-----------------------------------------------------------------------------# Copyright (c), Nicolas P. Rougier. All rights reserved.# distributed under the (new) BSD License. See LICENSE.txt for more info.#-----------------------------------------------------------------------------import NumPy as Npimport Matplotlib.pyplot as Pltplt.figure (figsize= (8,5), dpi=80) ax = plt.subplot (111) ax.spines[' right '].set _color (' none ') ax.spines[' top '].set_color (' None ') ax.xaxis.set_ticks_position (' bottom ') ax.spines[' bottom '].set_ Position (' data ', 0)) ax.yaxis.set_ticks_position (' left ') ax.spines[' left '].set_position ((' data ', 0)) X = Np.linspace (-np.pi, Np.pi, 256,endpoint=true) C,s = Np.cos (x), Np.sin (x) plt.plot (x, C, color= "Blue", linewidth=2.5, linestyle= "-") Plt.plot (x, S, color= "Red", linewidth=2.5, linestyle= "-") Plt.xlim (X.min () *1.1, X.max () *1.1) plt.xticks ([-np.pi,-NP.PI/2, 0, NP.PI/2, Np.pi], [R ' $ -\pi$ ', R ' $-\pi/2$ ', R ' $0$ ', R ' $+\pi/2$ ', R ' $+\pi$ ']) Plt.ylim (C.min () *1.1,c.max () *1.1) plt.yticks ([-1, 0, +1], [R ' $-1$ ', R ' $0$ ', R ' $+1$ ']) plt.show () 

The results shown are:

Legends and annotations

The legend is very simple, the following code can be resolved:

Plot (x, C, color= "Blue", linewidth=2.5, linestyle= "-", label= "cosine") plot (x, S, color= "Red", linewidth=2.5, linestyle= "-", label= "sine") Legend (loc= ' upper left ')

It is good to specify the label property in plot, and finally call the next legend function to determine the location of the legend, which is generally ' upper left '.

Note on a bit of trouble, to use the annotate command, quite complicated, for the time being do not want to see, let's stick a complete code and it:

#-----------------------------------------------------------------------------# Copyright (c), Nicolas P. Rougier. All rights reserved.# distributed under the (new) BSD License. See LICENSE.txt for more info.#-----------------------------------------------------------------------------import NumPy as Npimport Matplotlib.pyplot as Pltplt.figure (figsize= (8,5), dpi=80) ax = plt.subplot (111) ax.spines[' right '].set _color (' none ') ax.spines[' top '].set_color (' None ') ax.xaxis.set_ticks_position (' bottom ') ax.spines[' bottom '].set_ Position (' data ', 0)) ax.yaxis.set_ticks_position (' left ') ax.spines[' left '].set_position ((' data ', 0)) X = Np.linspace (-np.pi, Np.pi, 256,endpoint=true) C,s = Np.cos (x), Np.sin (x) plt.plot (x, C, color= "Blue", linewidth=2.5, linestyle= "-", label= "cosine") Plt.plot (x, S, color = "Red", linewidth=2.5, linestyle= "-", label= "sine") Plt.xlim (X.min () *1.1, X.max () *1.1) plt.xticks ([-np.pi,-NP.PI/2, 0 , NP.PI/2, Np.pi], [R ' $-\pi$ ', R ' $-\pi/2$ ', R ' $0$ ', R ' $+\pi/2$ ', R ' $+\pi$ ']) Plt.ylim (c.min() *1.1,c.max () *1.1) Plt.yticks ([-1, +1], [R ' $-1$ ', R ' $+1$ ']) t = 2*np.pi/3plt.plot ([T,t],[0,np.cos (t)], color = ' Blue ', linewidth=1.5, linestyle= "--") Plt.scatter ([T,],[np.cos (t),], a, color = ' Blue ') plt.annotate (R ' $\sin (\frac{2\pi}{3} ) =\frac{\sqrt{3}}{2}$ ', xy= (T, Np.sin (t)), xycoords= ' data ', xytext= (+10, +30), textcoords= ' offset points ', fontsize=16 , Arrowprops=dict (arrowstyle= ", connectionstyle=" arc3,rad=.2 ")) Plt.plot ([T,t],[0,np.sin (t)], color = ' red ', linewidth=1.5, linestyle= "--") Plt.scatter ([T,],[np.sin (t),], a, color = ' red ') plt.annotate (R ' $\cos (\frac{2\pi}{3}) =-\frac{1}{2}$ ', xy= (T, Np.cos (t)), xycoords= ' data ', xytext= ( -90, -50), textcoords= ' offset points ', fontsize=16, ARROWP Rops=dict (arrowstyle= ", connectionstyle=" arc3,rad=.2 ")) plt.legend (loc= ' upper left ', Frameon=false) Plt.savefig (".. /figures/exercice_9.png ", dpi=72) Plt.show ()

is still very high-energy ...

Summarize

"Recommended"

1. Python Free video tutorial

2. Python Basics Getting Started tutorial

3. Python's application in Data science

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.