How to draw with the drawing library in Python

Source: Internet
Author: User
Matplotlib is Python's most famous drawing library, this article has shared the use of matplotlib+numpy to draw a variety of methods of drawing examples, including fill chart, scatter plot (scatter plots),. Bar chart (bar plots), contour map (contour plots), bitmap and 3D diagram, the need for friends can refer to, let's take a look at it.

Objective

Matplotlib is Python's most famous drawing library, which provides a complete set of command APIs similar to those of MATLAB, making it ideal for interactive mapping. In this paper, we will analyze several diagrams which are commonly used in the analysis of Matplot in the form of examples. These include fill plots, scatter plots (scatter plots),. Bar charts (bar plots), contour plots (contour plots), bitmap plots, and 3D graphs, let's take a look at the detailed introduction below:

First, fill diagram

Reference Code


From Matplotlib.pyplot import *x=linspace ( -3,3,100) y1=np.sin (x) y2=np.cos (x) Fill_between (x,y1,y2,where= (y1>=y2) , color= ' Red ', alpha=0.25) Fill_between (x,y1,y2,where= (y<>y2), color= ' green ', alpha=0.25) plot (x,y1) Show ()

Brief analysis

The main use of this is the fill_between function. This function is well understood, which is the array of incoming x-axis and the two y-axis array that needs to be filled, then the range of padding is used where= to determine the area of the fill, and finally, the fill color, transparency, and other decorated parameters.

Of course fill_between , there are more advanced uses of the function, see Fill_between Usage or help documentation.

Two, scatter chart (scatter plots)

Reference Code


From matplotlib.pyplot import *n = 1024X = Np.random.normal (0,1,n) Y = Np.random.normal (0,1,n) T = np.arctan2 (y,x) Scatter (X , Y, s=75, c=t, alpha=.5) Xlim ( -1.5,1.5) Ylim ( -1.5,1.5) show ()

Brief analysis

First introduce the function of NumPy, it normal is obvious that this is the function of generating normal distribution. This function accepts three parameters, representing the average of the normal distribution, the standard deviation, and the length of the resulting array. Very well remembered.

Then the arctan2 function, which takes two parameters, represents the y array and the x array, and then returns the corresponding arctan(y/x) value, the result is radians.

The next use of the method of plotting scatter, scatter first of all, of course, the X and Y arrays, and then the s parameter represents the scale, that is, the size of the scatter; the c parameter is a color, and I pass it to an array of angles, which corresponds to the color of each point (though I don't know how it corresponds, But it seems to be a relative conversion based on the other elements in the array, it doesn't matter here, anyway the same color assigns the same value, and finally the alpha parameter, which indicates the transparency of the point.

scatterfor advanced usage of functions, see the official documentation scatter function or help documentation.

The final setting of the coordinate range is fine.

Three, bar chart (bar plots)

Reference Code


From matplotlib.pyplot import *n = 12X = Np.arange (n) Y1 = (1-x/float (n)) * Np.random.uniform (0.5,1.0,n) Y2 = (1-x/float (n)) * Np.random.uniform (0.5,1.0,n) bar (x, +y1, facecolor= ' #9999ff ', edgecolor= ' White ') bar (x,-y2, facecolor= ' #ff9999 ', edgecolor= ' White ') for x, y in Zip (x,y1): Text (x+0.4, y+0.05, '%.2f '% y, ha= ' center ', va= ' bottom ') for x, y in Zip (x,y2): TE XT (x+0.4,-y-0.05, '%.2f '% y, ha= ' center ', va= ' top ') Xlim (-.5,n) xticks ([]) Ylim ( -1.25,+1.25) yticks ([]) show ()

Brief analysis

Note To manually import the Pylab package, you will not find the bar ...

First, the NumPy function is used to arange generate an array of [0,1,2,..., N]. (can also use linspace)

Next, the NumPy uniform function is used to generate an evenly distributed array, with three parameters representing the lower bound, upper bounds and array lengths. Use this array to generate the data that needs to be displayed.

The bar function is then used, and the basic usage is similar to the previous plot and scatter, passing in the horizontal ordinate and some modifier parameters.

Then we need to use a for loop to display the numbers for the histogram: using Python's zip function to pair X and Y1 22, loop through, get the position of each data, and then use the text function to display a string at that position (note the detail adjustment in the position). The text is passed in the horizontal ordinate, to display the string, the ha parameter is drawn horizontally, and the VA parameter is drawn vertically aligned.

Finally adjust the lower coordinate range, and cancel the scale on the horizontal ordinate to maintain the appearance.

barYou can refer to the Bar function usage or help documentation for the specific usage of the function.

Iv. contour Map (contour plots)

Reference Code


From Matplotlib.pyplot import *def f (x, Y): Return (1-x/2+x**5+y**3) *np.exp (-x**2-y**2) n = 256x = Np.linspace ( -3,3,n) y = NP . Linspace ( -3,3,n) x, y = Np.meshgrid (x, y) Contourf (×, D, f (y), 8, alpha=.75, cmap=cm.hot) C = Contour (x, Y, f (y), 8, color S= ' black ', linewidth=.5) Clabel (C, inline=1, fontsize=10) show ()

Brief analysis

First of all, the contour graph is a three-dimensional figure, so we have to create a two-dollar function f, the value is controlled by two parameters (note that both parameters should be a matrix).

Then we need to meshgrid generate a three-dimensional mesh with the NumPy function, that is, the x-axis is specified by the first parameter, and the y-axis is specified by the second parameter. and return two of the matrix after the increment, in the future use these two matrices to generate an image.

Then use the coutourf function, the so-called Contourf, is probably the meaning of contour fill, only fill, not stroke; This function mainly accepts three parameters, namely the x, Y matrix and function values that were generated before, and then an integer, which is probably the density of the contour, There are default values, and then there is the problem of transparency and color matching, CMAP's color scheme is not much studied here.

Then there is the contour function, and it is clear that this function is used to stroke the line. Usage can be similar to the launch, do not explain, it is important to note that he returned an object, the object is generally retained for subsequent processing refinement.

The last is to use the Clabel function to express the height on the contour map, the previous contour object, and then the inline property, this indicates whether to clear the line below the number, for the sake of course, is cleared, and the default is 1, and then the width of the specified line, not explained.

Five, dot matrix diagram

Reference Code


From Matplotlib.pyplot import *def f (x, Y): Return (1-x/2+x**5+y**3) *np.exp (-x**2-y**2) n = 10x = Np.linspace ( -3,3,3.5*n) y = Np.linspace ( -3,3,3.0*n) x, y = Np.meshgrid (x, y) Z = f (x, y) imshow (z,interpolation= ' nearest ', cmap= ' bone ', origin= ' Lower ') Colorbar (shrink=.92) show ()

Brief analysis

The purpose of this code is to convert a matrix directly into a photo-like diagram, which is displayed in its entirety.

The preceding code is to generate a matrix Z without explanation.

Then use the imshow function, the descendant z can display a two-dimensional image, the color of the image is based on the value of the elements of the adaptive adjustment, followed by a number of modified parameters, such as color scheme (CMAP), 0 point location (origin).

Finally, the colorbar display of a color bar, you can not pass parameters, which passed in shrink the parameters used to adjust his length.

VI. 3D Figure

Reference Code


Import NumPy as Npfrom pylab import *from mpl_toolkits.mplot3d Import axes3dfig = figure () Ax = axes3d (fig) X = Np.arange (-4 , 4, 0.25) Y = Np.arange ( -4, 4, 0.25) X, y = Np.meshgrid (x, y) R = np.sqrt (x**2 + y**2) Z = Np.sin (R) ax.plot_surface (X, Y, Z, Rstride=1, cstride=1, Cmap=plt.cm.hot) Ax.contourf (X, Y, Z, zdir= ' z ', Offset=-2, Cmap=plt.cm.hot) Ax.set_zlim ( -2,2) show ()

Brief analysis

A bit of trouble, need to use the time to say it, but the principle is very simple, similar to contour map, first draw and then stroke, and finally set the height, are one thing.

Summarize

"Recommended"

1. Python Free video tutorial

2. Python Basics Getting Started tutorial

3. Python 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.