Python matplotlib introduction pyplot tutorial

Source: Internet
Author: User

This article is translated from the official matplotlib website.

Matplotlib. pyplot is a collection of command line-style functions, so that matplotlib works in a way similar to Matlab. Each pyplot function makes some changes to an image (figure), such as creating a new image, creating a new plot area in the image, and drawing a straight line in a plot area, add labels to a graph. Matplotlib. pyplot is stateful, that is, it stores the status of the current image and the plotting area. The new plotting function will function on the basis of the status of the current image.

import matplotlib.pyplot as pltplt.plot([1,2,3,4])plt.ylabel('some numbers')plt.show()

The X coordinate of is 1-3, and the Y coordinate is 1-4, because if you only provide a list or array to the plot () function, matplotlib considers this as a string of y values (Y vectors) and automatically generates x values (x vectors ). Python generally starts counting from 0, so the X vector has the same length as the y vector (4 here), but starts from 0, so the value of the X axis is [0, 1, 2, 3].

If you want to display the coordinates of the specified X axis, you can do the following:

plt.plot([1,2,3,4],[1,4,9,16])

You can also give it to PLT. the plot () function transmits multiple sequences (tuples or lists), each of which is an X-and y-vector pair, forming a curve in the figure, in this way, multiple curves exist in the same region.

To distinguish multiple curves of the same region, you can specify a parameter for each X or Y vector pair to indicate the curve format. The default parameter is 'B -', that is, a blue line. If you want to use a red dot to represent this curve, you can:

import matplotlib.pyplot as pltplt.plot([1,2,3,4],[1,4,9,16],'ro')plt.axis([0,6,0,20])

The axis () function accepts parameters such as [xmin, xmax, ymin, Ymax] and specifies the range of X and Y axis coordinates.

Matplotlib can not only use sequences (lists and metagroups) as parameters, but also numpy arrays. In fact, all sequences are internally converted into numpy arrays.

import numpy as npimport matplotlib.pyplot as pltt=np,arange(0.,5.,0.2)plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g^')

Control Curve attributes

A curve has many properties that we can set: the width of the curve, the style of the dotted line, and the anti-tooth ratio. There are multiple ways to set curve attributes:

1. Use keyword parameters:

plt.plot(x,y,linewidth=2.0)

2. Use the setter method of the line2d instance. Plot () returns a list of curves, such as line1, line2 = plot (x1, Y1, X2, Y2 ). after obtaining the curve returned by the plot () function, we use the setter method to set the curve attributes.

Line, = PLT. Plot (X, Y, '-') line. Set) antialliased (false) # disable anti-aliasing

3. Run the setp () command:

lines=plt.plot(x1,y1,x2,y2)plt.setp(lines,color='r',linewidth=2.0)plt.setp(lines,'color','r','linewidth','2.0')

Process Multiple Graphs and Axe

Both MATLAB and pyplot have the current graph and current axe concept. All plotting commands work on the current axe.

The function GCA () returns the current axe, GCF () returns the current graph.

import numpy as npimport matplotlib.pyplot as pltdef f(t):    return np.exp(-t) * np.cos(2*np.pi*t)t1 = np.arange(0.0, 5.0, 0.1)t2 = np.arange(0.0, 5.0, 0.02)plt.figure(1)plt.subplot(211)plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')plt.subplot(212)plt.plot(t2, np.cos(2*np.pi*t2), 'r--')

The figure () command is optional because figure (1) is created by default, and subplot (111) is also created by default. The subplot () command specifies numrows, numcols, and fignum. The value range of fignum is from 1 to numrows * numcols. If numrows * numcols is less than 10, the comma in the subplot () command is optional. Therefore, subplot (211, 1) is exactly the same as subplot.

If you want to manually place axe instead of placing it in a rectangle, you can use the axes () command. The parameter here is axes ([left, bottom, width, height]). the value range of each parameter is (0, 1 ).

You can use multiple figure () to create multiple graphs. Each graph can have multiple axe and subplot:

import matplotlib.pyplot as pltplt.figure(1)                # the first figureplt.subplot(211)             # the first subplot in the first figureplt.plot([1,2,3])plt.subplot(212)             # the second subplot in the first figureplt.plot([4,5,6])plt.figure(2)                # a second figureplt.plot([4,5,6])            # creates a subplot(111) by defaultplt.figure(1)                # figure 1 current; subplot(212) still currentplt.subplot(211)             # make subplot(211) in figure1 currentplt.title('Easy as 1,2,3')   # subplot 211 title

You can use the CLF () and linoleic () commands to clear the current figure and current axe.

If you create many graphs, you need to use the close () command to release the memory occupied by the graph. If you only close the graph displayed on the screen, the memory space will not be released.

Process text

The text () command can be used to add text anywhere. xlabel (), ylabel (), and title () can be used to add text to the X axis, Y axis, and title.

import numpy as npimport matplotlib.pyplot as pltmu, sigma = 100, 15x = mu + sigma * np.random.randn(10000)# the histogram of the datan, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)plt.xlabel('Smarts')plt.ylabel('Probability')plt.title('Histogram of IQ')plt.text(60, .025, r'$\mu=100,\ \sigma=15$')plt.axis([40, 160, 0, 0.03])plt.grid(True)

Each text () command returns a matplotlib. text. Text instance. Just like the previous processing curve, you can use the setp () function to pass keyword parameters to customize text attributes.

t=plt.xlabel('my data',fontsize=14,color='red')

Use mathematical expressions in the text

Matplotlib accepts the Text expression in any Text.

The Tex expression is surrounded by two dollar symbols. For example, the Tex expression is as follows:

plt.title(r'$\sigma_i=15$')

References:

[1] Pyplot Tutorial

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.