Examples of multiple plotting methods using matplotlib + numpy, matplotlibnumpy

Source: Internet
Author: User

Examples of multiple plotting methods using matplotlib + numpy, matplotlibnumpy

Preface

Matplotlib is the most famous Drawing Library in Python. It provides a complete set of command APIs similar to matlab and is very suitable for interactive plotting. This article analyzes several commonly used charts supported by matplot in the form of examples. This includes a fill chart, a scatter chart (scatter plots), a bar plots, a contour plots, a lattice chart, and a 3D graph. Let's take a look at the details below:

I. Filling chart

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)plot(x,y2)show()

Brief Analysis

Here we mainly usefill_betweenFunction. This function is easy to understand, that is, to pass in the array of the X axis and the two Y axis arrays to be filled; then, to pass in the fill range, usewhere=To determine the filling area. You can add parameters such as fill color and transparency.

Of coursefill_betweenFor more advanced functions, see fill_between usage or help.

Ii. scatter Plot (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, we will introducenormalFunction. Obviously, this is a function that generates a normal distribution. This function accepts three parameters, indicating the average value and standard deviation of the normal distribution, and the length of the generated array. It's easy to remember.

Thenarctan2Function. This function accepts two parameters, representing array y and array x respectively, and then returns the correspondingarctan(y/x)The result is in radians.

Next we usescatterFirst, the array x and y are input, and then the s parameter represents scale, that is, the size of the scatter; the c parameter represents color, and I will pass it an array based on the angle, it corresponds to the color of each vertex (although I don't know how it corresponds, it seems that it is a relative Conversion Based on other elements in the array. It doesn't matter here, assign the same value to the same color ).alphaParameter, indicating the transparency of the vertex.

AsscatterFor more information about functions, see scatter function or help.

Finally, set the coordinate range.

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): text(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 that you must manually import the pylab package. Otherwise, bar cannot be found...

First, use numpy'sarangeThe function generates a [0, 1, 2 ,..., N] array. (Linspace can also be used)

Next, use numpy'suniformThe function generates an even Distributed Array. The input three parameters indicate the lower bound, upper bound, and length of the array. Use this array to generate the data to be displayed.

Then the bar function is used. The basic usage is similar to that of the previous plot and scatter. The X-axis and Y-axis parameters are input.

Then we need to useforLoop to display numbers for the bar chart: Use python'szipThe function pairs X and Y1 and cyclically traverses them to obtain the position of each data.textThe function displays a string at this position (pay attention to the location details ). Input the horizontal and vertical coordinates of text, the string to be displayed,haHorizontal alignment is set for parameters and vertical alignment is set for va parameters.

Finally, adjust the coordinate range and cancel the scale on the horizontal and vertical coordinates to keep the appearance beautiful.

AsbarFor details about the Function usage, refer to bar function usage or help document.

4. 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(X, Y, f(X,Y), 8, alpha=.75, cmap=cm.hot)C = contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)clabel(C, inline=1, fontsize=10)show()

Brief Analysis

First, we need to make it clear that the contour map is a three-dimensional graph. Therefore, we need to establish a binary function f With the value controlled by two parameters. (Note that both parameters should be matrices ).

Then we need to use numpy'smeshgridThe function generates a 3D mesh, that is, the X axis is specified by the first parameter, and the Y axis is specified by the second parameter. And returns the matrix after two dimension increases. In the future, these two matrices will be used to generate images.

Next we will usecoutourfThe function is called the limit F, which is probably the meaning of the contour fill. It only fills in and does not show edges. This function mainly accepts three parameters, they are the previously generated x and y matrices and function values, followed by an integer, which indicates the density of the contour line and has default values. Then there is a problem with transparency and color, the color scheme of cmap is not studied here.

ThencontourFunction. Obviously, this function is used to describe the line. The usage can be similar to the Introduction. If you do not want to explain it, you need to note that it returns an object. This object is generally retained for further processing.

The clabel function is used to represent the height on the contour map.contourObject, and theninlineAttribute, which indicates whether to clear the line below the number. The line is cleared for the sake of appearance, and the default value is 1. The width of the line is specified ,.

5. lattice Map

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 directly convert a matrix into a picture like a photo for complete display.

The preceding Code generates a matrix Z, which is not explained.

Then we useimshowThe function is used to display a two-dimensional image. The color of the image is adjusted according to the value of the element, followed by some modifier parameters, for example, the color scheme (cmap) and the zero point (origin ).

Last usecolorbarDisplay a color bar. You can skip this parameter.shrinkThe parameter is used to adjust its length.

Vi. 3D images

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

It is a little troublesome. Let's talk about it when it is necessary. But the principle is also very simple. It is similar to a contour map. It is the same thing to draw a picture first, then draw a line, and finally set the height.

Summary

The above is all about this article. I hope this article will help you learn or use python. If you have any questions, please leave a message, thank you for your support.

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.