Matplotlib Illustration: Pyplot, Pylab module and drawing parameters

Source: Internet
Author: User
Tags arithmetic cos dashed line numeric value rand

http://blog.csdn.net/pipisorry/article/details/40005163 Matplotlib.pyplot Drawing instance

{Using the Pyplot module}
matplotlib draw line, bar/rectangular area

Import NumPy as NP
import Matplotlib.pyplot as plt
t = Np.arange ( -1, 2,.)
s = Np.sin (2 * np.pi * t)

PLT . Plot (T,s)
# Draw a thick red hline at y=0 that spans the xrange
L = plt.axhline (linewidth=4, color= ' R ')
PLT.A XIs ([-1, 2,-1, 2])
plt.show ()
plt.close ()

# Draw a default hline at Y=1 that spans the xrange
Plt.plot (t , s)
L = plt.axhline (Y=1, color= ' B ')
plt.axis ([-1, 2,-1, 2]) plt.show () plt.close ()
# Draw

A Thick Blue VLine at x=0 that spans upper quadrant of the Yrange
Plt.plot (t,s)
L = plt.axvline (x=0, ymin=0, L inewidth=4, color= ' B ')
plt.axis ([-1, 2,-1, 2])
plt.show ()
plt.close ()

# Draw a default hline at y=. 5 that spans the middle half of the axes
plt.plot (t,s)
L = plt.axhline (y=.5, xmin=0.25, xmax=0.75)
plt. Axis ([-1, 2,-1, 2])
plt.show ()
plt.close ()

plt.plot (t,s)
p = plt.axhspan (0.25, 0.75, facecolor= ' 0.5 ', alpha=0.5)
p = plt.axvspan (1.25, 1.55, facecolor= ' G ', alpha=0.5)
Plt.axis ([-1, 2,-1, 2])
plt.show ()
Effect Chart Show

Note: Set the value of the corresponding position of the line display: Plt.text (max_x, 0, str (round (max_x, 2)), that is, directly in the specified coordinates to write text, do not know whether there are other methods.

[Matplotlib.pyplot.axhline] another way to draw a line

Plt.hlines (Hline, XMIN=PLT.GCA (). Get_xlim () [0], XMAX=PLT.GCA (). Get_xlim () [1], Linestyles=line_style, Colors=color)
Histogram

Plt.hist (songs_plays, bins=50,range= (0, 50000), color=' LightBlue', normed=true)

The note:normed is to draw the y-coordinate proportionally, not the number.


hist into plot line chart

Plt.hist directly to draw data is hist graph

Plt.hist (z, bins=500, normed=true)
hist Graph into line chart
CNTs, bins = Np.histogram (Z, bins=500, normed=true)
bins = (Bins[:-1] + bins[1:])/2
plt.plot (bins, CNTs)

[NumPy Tutorial-statistical function: histogram]
Scatter, ladder, histogram, fill chart Histogram bar ()

The length of each column represents the size of the value, which is typically used to compare two or more sets of values.
The first parameter of bar () is the horizontal coordinate of the left edge of each pillar; the second parameter is the height of each column; The third parameter specifies the width of all columns, and when the third parameter is a sequence, the width can be specified for each column. Bar () does not automatically modify colors.

n = Np.array ([0,1,2,3,4,5])
x = Np.linspace ( -0.75, 1, m)

fig, axes = plt.subplots (1, 4, figsize= (12,3))

ax Es[0].scatter (x, x + 0.25*NP.RANDOM.RANDN (len (x))

axes[1].step (n, n**2, lw=2)

Axes[2].bar (n, n**2, align=) Center ", width=0.5, alpha=0.5)

axes[3].fill_between (x, X**2, x**3, color=" green ", alpha=0.5);

Note: Axes set title:axes.set_title ("Bar plot")

matplotlib Draw a Box chart (boxplots) and a violin chart (violinplots)

Import Matplotlib.pyplot as Plt

Import NumPy as NP

All_data = [Np.random.normal (0, STD, MB) for STD in range (1, 4)]

Fig = Plt.figure (figsize= (8,6))

Plt.boxplot (All_data,
Notch=false, # Box instead of notch shape
Sym= ' rs ', # Red squares for Outliers
vert=true) # Vertical Box aligmnent

Plt.xticks ([y+1 for y in range (len (all_data))], [' X1 ', ' x2 ', ' x3 ']]
Plt.xlabel (' Measurement x ')
t = plt.title (' Box plot ')
Plt.show ()

Violin chart
Plt.violinplot (All_data,
Showmeans=false,
Showmedians=true
)

[Matplotlib Drawing Box (boxplots) and violin map (violinplots)]

Hash Chart scatter () when using the plot () drawing, if the specified style parameter is a data point only, then a hash chart is plotted. However, the points drawn by this method cannot specify the color and size alone.
Scatter () The scatter Lietu you draw can specify the color and size of each point.
The first two parameters of scatter () are arrays, specifying the coordinates of the x and Y axes of each point respectively.
The s parameter specifies the size of the point, and the value is proportional to the area of the point. It can be a number that specifies the size of all points, or an array that specifies the size of each point, respectively.
The c parameter specifies the color of each point, which can be a numeric value or an array. This uses a one-dimensional array to specify a numeric value for each point. Each value corresponds to a color through the color map table. The default color map has the blue and the minimum, and the red corresponds to the maximum value. When the C parameter is a two-dimensional array of shapes (n,3) or (n,4), the RGB color of each point is represented directly.
The shape of the marker parameter setting point can be a string representing the shape, or a tuple representing the two elements of the polygon, the first element represents the number of edges of the polygon, and the second element represents the style of the polygon, with a value range of 0, 1, 2, and 3. 0 represents a polygon, 1 is a star, 2 is radial, and 3 is a circle that ignores the number of edges.
The transparency of the Alpha parameter set point.
The LW parameter is set to the line width, and the LW is the abbreviation for lines width.
When the facecolors parameter is "None", the hash point does not have a fill color.
Scatter chart (change color, size)

Import NumPy as NP import Matplotlib.pyplot as Plt

N = 50
x = Np.random.rand (N)
y = Np.random.rand (N)
Area = Np.pi * (* Np.random.rand (N)) **2 # 0-Point radiuses
color = 2 * Np.pi * Np.random.rand (N)
Plt.scatter (x, Y, S=area, C=color, alpha=0.5, CMAP=PLT.CM.HSV)
Plt.show ()

matplotlib A scatter plot to add a comment to a point

Plt.scatter (data_arr[:, 0], data_arr[:, 1], c=class_labels) for
I, Class_label in Enumerate (class_labels):
    Plt.annotate (Class_label, (data_arr[:, 0][i], data_arr[:, 1][i])
[Matplotlib scatter plot with different text at each data point]

[Matplotlib.pyplot.scatter] logarithmic coordinate graph

The X-y axis coordinates of the chart plotted by plot () are arithmetic coordinates.
There are three functions to draw a logarithmic graph: SEMILOGX (), Semilogy (), and Loglog (), which draw a chart with the x-axis as logarithmic coordinates, the y-axis as the logarithmic coordinates, and the two axes as logarithmic coordinates.
The following program uses 4 different coordinate systems to draw the frequency response curves of low-pass filters.
Among them, the upper left figure is the arithmetic coordinate system drawn by plot (), the upper-right figure is the x-axis logarithmic coordinate system drawn by SEMILOGX (), the lower-left figure is the y-axis logarithmic coordinate system drawn by semilogy (), and the lower-right figure is the double logarithmic coordinate system drawn by The frequency response curve, which is represented by using a double logarithmic coordinate system, is often called a baud graph.
Import NumPy as NP
Import Matplotlib.pyplot as Plt

W = Np.linspace (0.1, 1000, 1000)
p = np.abs (1/(1+0.1J*W)) # Calculating the frequency response of Low-pass filter
Plt.subplot (221)
Plt.plot (W, p, linewidth=2)
Plt.ylim (0,1.5)

Plt.subplot (222)
PLT.SEMILOGX (W, p, linewidth=2)
Plt.ylim (0,1.5)

Plt.subplot (223)
Plt.semilogy (W, p, linewidth=2)
Plt.ylim (0,1.5)

Plt.subplot (224)
Plt.loglog (W, p, linewidth=2)
Plt.ylim (0,1.5)

Plt.show ()

Polar coordinate diagram

The polar coordinate system is a completely different coordinate system from the Cartesian coordinate system, and the point in the polar coordinate system is represented by an angle and a distance from a relative center point. Polar (theta, R, **kwargs)
You can polar () directly create polar coordinates and draw curves in them. You can also create a polar graph by setting the polar argument to true by using the subplot () in your program to create a child graph, and then call Plot () to draw in a polar-coordinate child diagram. Example 1

Fig = Plt.figure ()
AX = fig.add_axes ([0.0, 0.0,. 6,. 6], Polar=true)
t = linspace (0, 2 * pi, 100)
Ax.plot (T, T, color= ' Blue ', lw=3);

Example 2

Import NumPy as NP
Import Matplotlib.pyplot as Plt

theta = Np.arange (0, 2*np.pi, 0.02)
Plt.subplot (121, Polar=true)
Plt.plot (Theta, 1.6*np.ones_like (theta), linewidth=2) #绘制同心圆
Plt.plot (3*theta, THETA/3, "--", linewidth=2)

Plt.subplot (122, Polar=true)
Plt.plot (Theta, 1.4*np.cos (5*theta), "--", linewidth=2)
Plt.plot (Theta, 1.8*np.cos (4*theta), linewidth=2)
Plt.rgrids (Np.arange (0.5, 2, 0.5), angle=45)
Plt.thetagrids ([0, 45])

Plt.show ()
Note:rgrids () Sets the radius size of the concentric grid and the angle of the text callout. So there are three dotted circles in the right figure, 0.5, 1.0, and 1.5 in radius, which are arranged along the 45° line.
Thetagrids () sets the angle of the radiation grid, so there are only two rays in the right image, the angle is 0° and 45° respectively.

[Matplotlib.pyplot.polar (*args, **kwargs)] isoline map uses isoline graphs to represent two-dollar functions z=f (x,y)

A

So-called isoline is a smooth curve that is connected by points of equal value to the function. An isoline can visually represent a change in the value of a two-valued function, for example, where the contours are dense, where the value of the function varies considerably. The contour () and Contourf () can be used to depict contours in the
Matplotlib, and the difference is that Contourf () results in an isoline with a fill effect.
Import NumPy as NP
Import Matplotlib.pyplot as Plt

y, x = np.ogrid[-2:2:200j, -3:3:300j]
z = x * NP.EXP ( -x**2-y**2)

extent = [Np.min (x), Np.max (x), Np.min (y), Np.max (y)]

Plt.figure (figsize= (10,4))
Plt.subplot (121)
cs = Plt.contour (z, extent=extent)
Plt.clabel (CS)
Plt.subplot (122)
Plt.contourf ( X.reshape ( -1), Y.reshape ( -1), z)
Plt.show ()
in order to 淸 the Chu area to the X and Y axes, this gives them a different range of values and dividing times. This gets the shape of the array z (200, 300), Its No. 0 axis corresponds to the x axis of the y axis and 1th axis.
Call Contour () draws an isoline graph of array z, and the second argument is 10, which means that the range of values for the entire function is divided into 10 ranges, which means that there will be 9 contours in the contour graph shown. You can use the extent parameter to specify the data range for the x-axis and y-axis of an isoline chart. The
Contour () returns a Quadcontourset object, passing it to Clabel (), which is the corresponding value of the Isoline.
Call Contourf () to draw an isoline chart that divides the range of values into 20 parts, with a fill effect. Here's another way to set the X, Y axis range, where the first two parameters are the x-axis and y-axis sampling points used to compute the array z, and the two arrays must be one-dimensional.
use Isoline to draw an implicit function f (x,y) =0 curve

Obviously, it is not possible to create an equal margin group to represent the value of a variable, and then to calculate the y value of each x in the array, as you would draw a general function.

You can use Isoline to solve this problem, obviously the implicit function of the curve is the value equals 0 of the line.
The curve of the program drawing function at f (x,y) =0 and F (x,y)-0.1 = 0 o'clock.
Import NumPy as NP
Import Matplotlib.pyplot as Plt

Y, x = np.ogrid[-1.5:1.5:200j, -1.5:1.5:200j]
F = (x**2 + y**2) **4-(x**2-y**2) **2
Plt.figure (figsize= (9,4))
Plt.subplot (121)
extent = [Np.min (x), Np.max (x), Np.min (y), Np.max (y)]
CS = Plt.contour (f, extent=extent, Levels=[0, 0.1], colors=["B", "R"], linestyles=["solid", "dashed"], linewidths=[2, 2])
Plt.subplot (122)
For C in cs.collections:
data = C.get_paths () [0].vertices
Plt.plot (data[:,0], data[:,1], Color=c.get_color () [0], linewidth=c.get_linewidth () [0])

Plt.show ()

The contour () levels parameter specifies the function value of the drawn contour, where the levels parameter is set to [0,0.1], so two contours are eventually drawn.
The observation chart shows that the =0 blue solid line representing the implicit function f (x) is not completely contiguous, and it is composed of many isolated segments in the middle part of the graph. Because contours are infinitely close to the origin, no matter how the value space of the function f is subdivided, there will always be places that cannot be separated, resulting in isolated small areas of the graph.

The red dotted line, which represents the implicit function f (x,y) =0, is closed and contiguous. Contour () returns the object Quadcontourset

You can get the data for each point on the contour by contour (), and we observe the variable cs in Ipython, which is a Quadcontourset object:
The collections property of the CS object is a list of contours, each of which is represented by a Linecollection object:
>>> cs.collections
<a List of 2 collections. Linecollection objects>
Each Linecollection object has its own color, line style, line width and other attributes, note that the results of these properties there is a layer of encapsulation, to get its No. 0 element is the real configuration:
>>> c0.get_color () [0]
Array ([0., 0., 1., 1.])
>>> c0.get_linewidth () [0]
2
It is known from the class name that the Linecollection object is a set of curves, so it can represent contours that are composed of multiple lines like blue solid lines. Its get_paths () method obtains all the paths that make up the contour line, in this case the blue solid line
The contour represented by 42 paths:
>>> Len (cs.collections[0].get_paths ())
42
A path is an object that, through its vertices property, obtains the coordinates of all the points on the path:
>>> path = cs.collections[0].get_paths () [0]
>>> Type (PATH)
<class ' Matplotlib.path.Path ' >
>>> path.vertices
Array ([[-0.08291457,-0.98938936],
[-0.09039269,-0.98743719],
...,
[-0.08291457,-0.98938936]]
The above program Plt.subplot (122) finds the path representing the isoline from the contour set CS and draws it out using plot ().

Del Piero Blog



Matplotlib.pylab Drawing Instance

{Using the Pylab module}

Matplotlib also provides a module called Pylab, which includes many functions commonly used in NumPy and pyplot modules to facilitate rapid computation and drawing by users, and is ideal for use in Ipython interactive environments. Here, load the Pylab module using the following method:

>>> Import Pylab as pl
Note: Import Pyplot as PLT can also
Two types of common graphs

Line and scatter plots (using the plot () command), histogram (using the hist () command)

10 percent Line charts & Scatter chart lines and scatter plots

Line Chart line plots (lines associated with a set of x and Y values)

Import NumPy as NP
Import Pylab as Pl
x = [1, 2, 3, 4, 5]# make an array of x values
y = [1, 4, 9, 25]# make a array of y values for each x value
Pl.plot (x, y) # use Pylab to plot x and Y
Pl.show () # show the "Plot on" screen


Plot (x, y)        # Plot x and y using default line style and color
plot (x, y, ' Bo ')  # Plot x and y using blue circle Markers
Plot (y)           # Plot y using X as index array 0..n-1
plot (y, ' r+ ')     # ditto, but with red plusses

Plt.plot (KS, wssses, marker= ' * ', markerfacecolor= ' R ', linestyle= '-', color= ' B ')

Scatter plot scatter plots

Change Pl.plot (x, y) to Pl.plot (x, y, ' o ')


Landscaping making things look pretty

line colors Changing the lines color

Red: Change Pl.plot (x, y, ' o ') to Pl.plot (x, Y, ' or ')

line styles Changing the lines style

Dashed line: Plot (X,y, '--')

marker style Changing the marker style

Blue Star Markers:plot (x,y, ' b* ')

See the drawing parameters in appendix-Matplotlib in detail

Diagram and axis headings and axis coordinate limits Plot and axis titles and limits

Import NumPy as NP
Import Pylab as Pl
x = [1, 2, 3, 4, 5]# make an array of x values
y = [1, 4, 9, 25]# make a array of y values for each x value
Pl.plot (x, y) # use Pylab to plot x and Y
Pl.title (' Plot of y vs. X ') # give Plot a title
Pl.xlabel (' x axis ') # Make axis labels
Pl.ylabel (' Y axis ')
Pl.xlim (0.0, 7.0) # Set Axis limits
Pl.ylim (0.0, 30.)
Pl.show () # show the "Plot on" screen

draw multiple graphs on a coordinate system plotting more than one plot on the same set of axes

In turn, the drawing can

Import NumPy as NP
Import Pylab as Pl 
x1 = [1, 2, 3, 4, 5]# make x, y arrays for each graph
y1 = [1, 4,

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.