Pyplot tutorial,Pyplot官方教程自翻譯

王明輝發表於2018-02-06

 

matplotlib.pyplot is a collection 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 various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that “axes” here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).

 

matplotlib.pyplot是一個命令列風格的函式集合,使matplotlib像MATLAB一樣工作。每個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 from 1-4. If you provide a single list or array to the plot() command, matplotlib assumes it is a sequence of y values, and automatically generates the x values for you. Since python ranges start with 0, the default x vector has the same length as y but starts with 0. Hence the x data are [0,1,2,3].

你可能感到奇怪,為什麼x軸的範圍是多0到3而y軸是從1到4。如果你只給plot() 命令提供了一個列表或陣列引數,matplotlib認為它是一個y值的序列,然後自動生成x值。因為Python的序列範圍從0開始,所以預設的x向量與y向量有相同的長度,但是x從0開始。因此,x的值是[0,1,2,3]。

 

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

plot()是個通用【或萬能的】(versatile command)的命令,它有一個可變數量的引數。例如,繪製x和y,你可以發出以下命令:

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

 

For every x, y pair of arguments, there is an optional third argument which 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 you concatenate a color string with a line style string. The default format string is ‘b-‘, which is a solid blue line. For example, to plot the above with red circles, you would issue

對於每一對x和y引數,有一個第三個引數可以設定圖的顏色和線型。字母和符號的字串格式來自MATLAB,顏色字母與線型字元緊貼。預設的字串格式為“b-”,這是一條實心藍色線。例如,要用紅色圓點繪製上圖,你要使用以下命令:

import matplotlib.pyplot as plt

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

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

plt.show()

(Source codepngpdf)

 

 

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

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

檢視 plot()文件以獲得完整的線型和格式化字串。 axis() 命令在上例中接受了一個形如 [xmin, xmax, ymin, ymax]的列表並且說明了座標的視口(viewport)【什麼是視口?】

如果matplotlib只限於使用list工作,那它對於資料處理就沒什麼價值了。一般來講,你會使用numpy陣列。事實上,所有序列(sequence)都會在內部轉為numpy陣列。下面的例子展示了在一條命令中使用陣列用不同的格式繪製多條線條。

import numpy as np

import matplotlib.pyplot as plt

 # evenly sampled time at 200ms intervals

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

 # red dashes, blue squares 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 are several ways to set line properties

對於線圖,有很多可以控制的屬性:線條寬度、線條樣式、抗鋸齒等等。點選matplotlib.lines.Line2D檢視詳細。有很多方法可以設定線的屬性:

  • 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 off antialising
  • 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.

下面是Line2D的有效屬性

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() function with a line or lines as argument

呼叫setp() 函式,以一條或多條線圖作為引數傳入,即可獲得一個可設定的線圖屬性列表:

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

In [70]: plt.setp(lines)

  alpha: float

  animated: [True | False]

  antialiased or 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 plotting commands apply to the current axes. The function gca() returns the current axes (a matplotlib.axes.Axes instance), and gcf() returns the current figure (matplotlib.figure.Figure instance). Normally, you don’t have to worry about this, because it is all taken care of behind the scenes. Below is a script to create two subplots.

MATLAB和pyplot,有當前圖形和座標的概念。所有繪製命令都是對當前座標進行操作。gca()函式返回當前座標系(一個matplotlib.axes.Axes例項),gcf() 返回當前圖形。通常你不必擔心,因為這些都是幕後工作。下面是建立兩個子圖的指令碼:

import numpy as np

import matplotlib.pyplot as plt

 

def 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--')

plt.show()

(Source codepngpdf)

 

 

The figure() command here is optional because figure(1) will be created by default, just as a subplot(111) will be created by default if you don’t manually specify any axes. The subplot() command specifies numrows, numcols, fignum where fignum ranges from 1 to numrows*numcols. The commas in the subplot command are optional if numrows*numcols<10. So subplot(211) is identical to subplot(2, 1, 1). You can create an arbitrary number of subplots and axes. If you want to place an axes manually, i.e., not on a rectangular grid, use the axes() command, which allows you to specify the location as axes([left, bottom, width, height]) where all values are in fractional (0 to 1) coordinates. See pylab_examples example code: axes_demo.py for an example of placing axes manually and pylab_examples example code: subplots_demo.py for an example with lots of subplots.

  figure() 命令在這裡是可選項,因為 figure(1) 是預設建立的,就像如果你不去手動建立任何座標系,那麼subplot(111)也會自動建立一個一樣。subplot()命令接受numrows、numcols、fignum 引數,fignum 範圍是從1到 numrows*numcols的乘積。如果numrows*numcols的乘積小於10,那麼逗號是可選項,可加可不加。所以subplot(211)與 subplot(2, 1, 1)完全相同。你可以在子圖和座標系中建立任意數。如果你要手動放置一個座標系,而不是在一個矩形的網格上,使用axes() 命令,它可以通過函式axes([left, bottom, width, height])來指定座標系的位置,這個座標系的值在0~1之間。檢視pylab_examples example code: axes_demo.py獲得手動設定軸線示例程式碼,檢視pylab_examples example code: subplots_demo.py獲得多子圖示例程式碼。

 

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

  隨著圖形編號的增加,你可以呼叫多次figure() 函式來建立多個圖形。當然,每個圖形都可以包含你期望的圖形和座標。

 

import matplotlib.pyplot as plt

plt.figure(1)                # the first figure

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

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

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

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

  

plt.figure(2)                # a second figure

plt.plot([4, 5, 6])          # creates a subplot(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() and the current axes with cla(). If you find it annoying that states (specifically the current image, figure and axes) are being maintained for you behind the scenes, don’t despair: this is just a thin stateful wrapper around an object oriented API, which you can use instead (see Artist tutorial)

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 is explicitly closed with close(). Deleting all references to the figure, and/or using the window manager to kill the window in which the figure appears on the screen, is not enough, because pyplot maintains internal references until close() is called.

  你可以使用clf() 函式清除當圖形,使用cla()清除當前座標。如果你覺得後臺保留狀態打擾了你,不要絕望:這只是圍繞著物件導向API的一個瘦狀態包,你可以使用。【這句沒明白】

   如果你正在製作多個圖形,你要意識到一件事情:如果不明確呼叫close()函式來關閉圖形,那麼圖形所佔記憶體就不會被完全釋放。刪除所有對圖形的引用,或者使用windows的工作管理員殺掉顯示在螢幕上的圖形視窗,這些都不夠,因為pyplot保持了內部的引用,直到呼叫close()顯式關閉。

 

Working with text

操作文字

 

The text() command can be used to add text in an arbitrary location, and the xlabel()ylabel() and title() are used to add text in the indicated locations (see Text introduction for a more detailed example)

  可以在任意位置使用 text()命令,xlabel()ylabel()、 title()用來在指定位置新增文字。(檢視Text introduction 得到更加詳細的示例)

import numpy as np

import matplotlib.pyplot as plt

 
# Fixing random state for reproducibility

np.random.seed(19680801)
 

mu, sigma = 100, 15

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

 

# the histogram of the data

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() commands return an matplotlib.text.Text instance. Just as with with lines above, you can customize the properties by passing keyword arguments into the text functions or using setp():

所有的 text()命令會返回一個matplotlib.text.Text例項。正像上圖所示,你可以通過向文字函式傳入引數或使用 setp()函式,來定製屬性。

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

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

這些屬性在Text properties and layout中有詳細描述。

Using mathematical expressions in text

在文字中使用數學表示式

matplotlib accepts TeX equation expressions in any text expression. For example to write the expressionin the title, you can write a TeX expression surrounded by dollar signs:

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

Matplotlib可以在任何文字表示式中接受TeX等式。例如,在標題中寫這個被$符號的TeX表示式:

The r preceding the title string is important – it signifies that the string is a raw string and not to treat backslashes as python escapes. matplotlib has a built-in TeX expression parser and layout engine, and ships its own math fonts – for details see Writing mathematical expressions. Thus you can use mathematical text across platforms without requiring a TeX installation. For those who have LaTeX and dvipng installed, you can also use LaTeX to format your text and incorporate the output directly into your display figures or saved postscript – see Text rendering With LaTeX.

  標題中的前導字母r很重要,它標誌著這個字串是原始字串,不要進行python的轉碼。Matplotlib有個內建的TeX表示式分析器和佈局引擎,承載它自己的數學字型,檢視詳細Writing mathematical expressions。這樣你就可以跨平臺使用數學文字而不需要安裝一個TeX軟體。對於那些安裝了LaTeX和dvipng的人,你也可以使用LaTeX來格式化你的文字,合併輸出目錄到你的顯示圖形或儲存指令碼,檢視Text rendering With LaTeX

Annotating text

The uses of the basic text() command above place text at an arbitrary position on the Axes. A common use for text is to annotate some feature of the plot, and the annotate() method provides helper functionality to make annotations easy. In an annotation, there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. Both of these arguments are (x,y) tuples.

import numpy as np
import matplotlib.pyplot as plt

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

 

(Source codepngpdf)

 

 

In this basic example, both the xy (arrow tip) and xytext locations (text location) are in data coordinates. There are a variety of other coordinate systems one can choose – see Basic annotation and Advanced Annotation for details. More examples can be found in pylab_examples example code: annotation_demo.py.

 

在這個基礎的例子裡,xy兩個座標(箭頭)和xytext位置(文字位置)都在資料座標裡。也有其它形式的座標系統可以選擇,檢視Basic annotation 和 Advanced Annotation檢視詳細資訊。在pylab_examples example code: annotation_demo.py可檢視更多示例。

 

Logarithmic and other nonlinear axes

對數和其它非線性座標

 

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

matplotlib.pyplot不僅支援線性座標尺度,也支援對數和分對數尺度(logarithmic and logit scales)。如果資料跨越了多個大小的順序,就會用到這個功能【這句話的意思是可能是同一個座標上有不同的度量尺度】。改變一個座標的尺度很容易:

plt.xscale(‘log’)

 

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

下面是對於y軸的相同資料不同尺度(scales)的四個繪圖(plot)

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.ticker import NullFormatter  # useful for `logit` scale

# Fixing random state for reproducibility

np.random.seed(19680801)

# make up some data in the 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 various axes 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 tick labels of the y-axis into empty strings with

# `NullFormatter`, to avoid cumbering the axis with too many labels.

 # 用“NullFormatter”把Y軸的子刻度清空,以避免太多顯示標籤

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

# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"

 # 適應子圖佈局,因為logit圖形會比普通圖形戰勝更多的空間,因為y軸刻度從1到10^{-3}

plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,wspace=0.35)
plt.show()

 (Source codepngpdf)

 

 

It is also possible to add your own scale, see Developer’s guide for creating scales and transformations for details.

 你也可以新增你自己的尺度,檢視Developer’s guide for creating scales and transformations獲得更詳細的資訊

 

相關文章