# Pyplot tutorial官方文档

Pyplot tutorial

matplotlib.pyplot is acollection of command style functions that make matplotlib work like MATLAB.Each pyplot function makes some change to a figure: e.g., creates a figure,creates a plotting area in a figure, plots some lines in a plotting area,decorates the plot with labels, etc. In matplotlib.pyplot variousstates are preserved across function calls, so that it keeps track of thingslike the current figure and plotting area, and the plotting functions aredirected to the current axes (please note that “axes” here and in most placesin the documentation refers to the axes part of a figure and notthe strict mathematical term for more than one axis).

matplotlib.pyplot是一个命令行风格的函数集合，使matplotlibMATLAB一样工作。每个pyplot 函数会对图形窗口(figure)做一些改变，例如：创建一个图形窗口、在图形窗口上创建一个绘图区(plotting area)、在绘图区上画一些线条、在线条上标注说明文字等等。在matplotlib.pyplot中，通过函数调用保留不同的状态，这样就可以对当前图形(figure)和绘图区(plotting area)保持跟踪，并且当前绘制函数(plotting functions)被导向到当前坐标系（请注意这里的“坐标”，在文档中的大多数地方，指的是图形窗口的坐标部分，而非严格意义上的数学术语）

import matplotlib.pyplot as plt

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

plt.ylabel('some numbers')

plt.show()

(Source codepngpdf)

You may be wondering why the x-axis ranges from 0-3 and the y-axis from1-4. If you provide a single list or array to the plot() command,matplotlib assumes it is a sequence of y values, and automatically generatesthe x values for you. Since python ranges start with 0, the default x vectorhas the same length as y but starts with 0. Hence the x data are [0,1,2,3].

plot() is aversatile command, and will take an arbitrary number of arguments. For example,to plot x versus y, you can issue the command:

plot()是个通用【或万能的】(versatilecommand)的命令，它有一个可变数量的参数。例如，绘制xy，你可以发出以下命令：

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

For every x, y pair of arguments, there is an optional third argumentwhich is the format string that indicates the color and line type of the plot.The letters and symbols of the format string are from MATLAB, and youconcatenate a color string with a line style string. The default format stringis ‘b-‘, which is a solid blue line. For example, to plot the above with redcircles, you would issue

importmatplotlib.pyplotasplt

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

plt.axis([0, 6, 0, 20])

plt.show()

(Source codepngpdf)

See the plot() documentationfor a complete list of line styles and format strings. The axis() command inthe example above takes a list of [xmin, xmax, ymin, ymax] andspecifies the viewport of the axes.

If matplotlib were limited to working with lists, it would be fairlyuseless for numeric processing. Generally, you will use numpy arrays.In fact, all sequences are converted to numpy arrays internally. The examplebelow illustrates a plotting several lines with different format styles in onecommand using arrays.

importnumpyasnp

importmatplotlib.pyplotasplt

# evenly sampled timeat 200ms intervals

t = np.arange(0., 5., 0.2)

# red dashes, bluesquares and green triangles

plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')

plt.show()

(Source codepngpdf)

Controlling line properties 控制线条属性

Lines have many attributes that you can set: linewidth, dash style,antialiased, etc; see matplotlib.lines.Line2D. There areseveral ways to set line properties

• Use keyword args:
• 使用关键字参数：

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

• Use the setter methods of a Line2D instance. plot returns a list of Line2D objects; e.g., line1, line2 = plot(x1, y1, x2, y2). In the code below we will suppose that we have only one line so that the list returned is of length 1. We use tuple unpacking with line, to get the first element of that list:
• 使用Line2D实例的设置方法。plot返回一个Line2D对象的列表，例如：line1,line2=plot(x1, y1, x2, y2)，在下面的代码中，假设只有一条线，这样返回的列表长度为1。我们把线条组成的元组拆包到变量line，得到列表的第1个元素。

·        line, = plt.plot(x, y, '-')

·        line.set_antialiased(False) # turn offantialising

• Use the setp() command. The example below uses a MATLAB-style command to set multiple properties on a list of lines. setp works transparently with a list of objects or a single object. You can either use python keyword arguments or MATLAB-style string/value pairs:
• 使用setp() 命令。下面的例子使用了MATLAB样式的命令在一个线条列表上设置多个属性。setp透明地与单个对象或多个对象的列表一起工作。既可以用python的关键字参数，也可以用MATLAB风格的“字符串/值”对。

·        lines = plt.plot(x1, y1, x2, y2)

·        # use keyword args 关键字参数

·        plt.setp(lines, color='r', linewidth=2.0)

·        # or MATLAB style string value pairs “字符串/值”对儿

·        plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

Here are the available Line2D properties.

 Property Value Type alpha float animated [True | False] antialiased or aa [True | False] clip_box a matplotlib.transform. Bbox instance clip_on [True | False] clip_path a Path instance and a Transform instance, a Patch color or c any matplotlib color contains the hit testing function dash_capstyle ['butt' | 'round' | 'projecting'] dash_joinstyle ['miter' | 'round' | 'bevel'] dashes sequence of on/off ink in points data (np.array xdata, np.array ydata) figure a matplotlib.figure. Figure instance label any string linestyle or ls ['-'|'--'|'-.'|':'|'steps'|...] linewidth or lw float value in points lod [True | False] marker ['+'|','|'.'|'1'|'2'|'3'|'4'] markeredgecolor or mec any matplotlib color markeredgewidth or mew float value in points markerfacecolor or mfc any matplotlib color markersize or ms float markevery [ None | integer | (startind, stride) ] picker used in interactive line selection pickradius the line pick selection radius solid_capstyle ['butt' | 'round' | 'projecting'] solid_joinstyle ['miter' | 'round' | 'bevel'] transform a matplotlib.transforms.Transform instance visible [True | False] xdata np.array ydata np.array zorder any number

To get a list of settable line properties, call the setp() functionwith a line or lines as argument

In [69]: lines = plt.plot([1, 2, 3])

In [70]: plt.setp(lines)

alpha: float

animated:[True | False]

antialiasedor aa: [True | False]

...snip

Working with multiple figures and axes

MATLAB, and pyplot,have the concept of the current figure and the current axes. All plottingcommands apply to the current axes. The function gca() returnsthe current axes (a matplotlib.axes.Axes instance),and gcf() returnsthe current figure (matplotlib.figure.Figure instance).Normally, you don’t have to worry about this, because it is all taken care ofbehind the scenes. Below is a script to create two subplots.

MATLABpyplot，有当前图形和坐标的概念。所有绘制命令都是对当前坐标进行操作。gca()函数返回当前坐标系（一个matplotlib.axes.Axes实例），返回当前图形。通常你不必担心，因为这些都是幕后工作。下面是创建两个子图的脚本：

importnumpyasnp

importmatplotlib.pyplotasplt

deff(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--')

plt.show()

(Source codepngpdf)

The figure() commandhere is optional because figure(1) will be created by default, just asa subplot(111) will be created by default if you don’t manuallyspecify any axes. The subplot() commandspecifies numrows, numcols, fignum where fignum rangesfrom 1 to numrows*numcols. The commas in the subplot commandare optional if numrows*numcols<10. So subplot(211) isidentical to subplot(2, 1, 1). You can create an arbitrary number ofsubplots and axes. If you want to place an axes manually, i.e., not on arectangular grid, use the axes() command,which allows you to specify the location as axes([left, bottom, width, height]) where allvalues are in fractional (0 to 1) coordinates. See pylab_examplesexample code: axes_demo.py for an example of placing axesmanually and pylab_examplesexample code: subplots_demo.py for an example with lots ofsubplots.

figure() 命令在这里是可选项，因为 figure(1) 是默认创建的，就像如果你不去手动创建任何坐标系，那么subplot(111)会自动创建一个一样。subplot()命令接受numrowsnumcolsfignum 参数，fignum 范围是从1 numrows*numcols的乘积。如果numrows*numcols的乘积小于10，那么逗号是可选项，可加可不加。所以subplot(211) subplot(2, 1, 1)完全相同。你可以在子图和坐标系中创建任意数。如果你要手动放置一个坐标系，而不是在一个矩形的网格上，使用axes() 命令，它可以通过函数axes([left, bottom, width, height])来指定坐标系的位置，这个坐标系的值在0~1之间。查看pylab_examplesexample code: axes_demo.py获得手动设置轴线示例代码，查看pylab_examplesexample code: subplots_demo.py获得多子图示例代码。

You can create multiple figures by using multiple figure() calls withan increasing figure number. Of course, each figure can contain as many axesand subplots as your heart desires:

importmatplotlib.pyplotasplt

plt.figure(1)               # the first figure

plt.subplot(211)             # the first subplotin the first figure

plt.plot([1, 2, 3])

plt.subplot(212)             # the second subplotin the first figure

plt.plot([4, 5, 6])

plt.figure(2)               # a second figure

plt.plot([4, 5, 6])          # creates asubplot(111) by default

plt.figure(1)                # figure 1 current;subplot(212) still current

plt.subplot(211)             # make subplot(211)in figure1 current

plt.title('Easy as 1, 2, 3') # subplot 211 title

You can clear the current figure with clf() andthe current axes with cla().If you find it annoying that states (specifically the current image, figure andaxes) are being maintained for you behind the scenes, don’t despair: this isjust a thin stateful wrapper around an object oriented API, which you can useinstead (see Artisttutorial)

If you are making lots of figures, you need to be aware of one more thing:the memory required for a figure is not completely released until the figure isexplicitly closed with close(). Deleting allreferences to the figure, and/or using the window manager to kill the window inwhich the figure appears on the screen, is not enough, because pyplot maintainsinternal references until close() is called.

Working with text

The text() commandcan be used to add text in an arbitrary location, and the xlabel()ylabel() and title() are usedto add text in the indicated locations (see Textintroduction for a more detailed example)

importnumpyasnp

importmatplotlib.pyplotasplt

# Fixing random statefor reproducibility

np.random.seed(19680801)

mu, sigma =100, 15

x = mu + sigma * np.random.randn(10000)

# the histogram of thedata

n, 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)

plt.show()

(Source codepngpdf)

All of the text() commandsreturn an matplotlib.text.Text instance.Just as with lines above, you can customize the properties by passing keywordarguments into the text functions or using setp():

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

These properties are covered in more detail in Textproperties and layout.

Using mathematical expressions in text

matplotlib accepts TeX equation expressions in any text expression. Forexample to write the expression   in the title, you can write a TeX expression surroundedby dollar signs:

Matplotlib可以在任何文本表达式中接受TeX等式。例如，在标题中写这个被$符号的TeX表达式： plt.title(r'$\sigma_i=15\$')

The r preceding the title string is important – it signifies that thestring is a raw string and not to treat backslashes as pythonescapes. matplotlib has a built-in TeX expression parser and layout engine, andships its own math fonts – for details see Writingmathematical expressions. Thus you can use mathematical text acrossplatforms without requiring a TeX installation. For those who have LaTeX anddvipng installed, you can also use LaTeX to format your text and incorporatethe output directly into your display figures or saved postscript – see Textrendering With LaTeX.

Annotating text

The uses of the basic text() commandabove place text at an arbitrary position on the Axes. A common use for text isto annotate some feature of the plot, and the annotate() methodprovides helper functionality to make annotations easy. In an annotation, thereare two points to consider: the location being annotated represented by theargument xy and the location of the text xytext. Both of thesearguments are (x,y) tuples.

importnumpyasnp

importmatplotlib.pyplotasplt

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)

s = np.cos(2*np.pi*t)

line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),

arrowprops=dict(facecolor='black', shrink=0.05),

)

plt.ylim(-2,2)

plt.show()

In this basic example, both the xy (arrowtip) and xytext locations (text location) are in data coordinates. There are avariety of other coordinate systems one can choose – see Basicannotation and AdvancedAnnotation for details. More examples can be found in pylab_examplesexample code: annotation_demo.py.

Logarithmic and other nonlinear axes

matplotlib.pyplot supportsnot only linear axis scales, but also logarithmic and logit scales. This iscommonly used if data spans many orders of magnitude. Changing the scale of anaxis is easy:

plt.xscale(‘log’)

An example of four plots with the same data and different scales for the yaxis is shown below.

importnumpyasnp

importmatplotlib.pyplotasplt

frommatplotlib.tickerimport NullFormatter  # useful for logit scale

# Fixing random statefor reproducibility

np.random.seed(19680801)

# make up some data inthe interval ]0, 1[

y = np.random.normal(loc=0.5, scale=0.4, size=1000)

y = y[(y >0) & (y <1)]

y.sort()

x = np.arange(len(y))

# plot with variousaxes scales

plt.figure(1)

# linear

plt.subplot(221)

plt.plot(x, y)

plt.yscale('linear')

plt.title('linear')

plt.grid(True)

# log

plt.subplot(222)

plt.plot(x, y)

plt.yscale('log')

plt.title('log')

plt.grid(True)

# symmetric log

plt.subplot(223)

plt.plot(x, y - y.mean())

plt.yscale('symlog', linthreshy=0.01)

plt.title('symlog')

plt.grid(True)

# logit

plt.subplot(224)

plt.plot(x, y)

plt.yscale('logit')

plt.title('logit')

plt.grid(True)

# Format the minor ticklabels of the y-axis into empty strings with

# NullFormatter, toavoid cumbering the axis with too many labels.

plt.gca().yaxis.set_minor_formatter(NullFormatter())

# Adjust the subplotlayout, because the logit one may take more space

# than usual, due toy-tick labels like "1 - 10^{-3}"

wspace=0.35)

plt.show()

(Source codepngpdf)

It is also possible to add your own scale, see Developer’sguide for creating scales and transformations fordetails.

11-26

05-16
05-17
01-07 3万+
09-14
01-08 1万+
11-27 5185
11-22 1万+
01-05 8万+