Pyplot tutorial

Intro to pyplot:

matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATlAB.

Generating visualizations with pyplot is very quick:

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

the x-axis ranges from 0-3 and the y-axis from 1-4

Since python ranges start with 0, the default x vector has the same length as y but starts with 0.

plot() is a versatile command, and will take an arbitrary number of arguments.

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

Formatting the style of your plot

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

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

The axis() command in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the viewport of the axes.

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.show()

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.

import matplotlib.pyplot as plt
import numpy as np

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

>>> import numpy as np
>>> t=np.arange(0.,5.,0.2)
>>> print(t)
[0.  0.2 0.4 0.6 0.8 1.  1.2 1.4 1.6 1.8 2.  2.2 2.4 2.6 2.8 3.  3.2 3.4
 3.6 3.8 4.  4.2 4.4 4.6 4.8]

Plotting with keyword strings
There are some instances where you have data in a format that lets you access particular variables with strings.

Matplotlib allows you provide such an object with the data keyword argument. If provided, then you may generate plots with the strings corresponding to these variables.

代码没看懂。

import matplotlib.pyplot as plt
import numpy as np

data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

Plotting with categorical variables

It is also possible to create a plot using categorical variables. Matplotlib allows you to pass categorical variables directly to many plotting functions.

没看懂代码

import matplotlib.pyplot as plt

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()

Controlling line properties 

Lines have many attributes that you can set: linewidth, dash style, antialiased.

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; 

line, = plt.plot(x, y, '-')
line.set_antialiased(False) # turn off antialiasing

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

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)

上面没看懂。

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

import matplotlib.pyplot as plt
import numpy as np

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

>>> t1=np.arange(0.0,5.0,0.1)
>>> t2=np.arange(0.0,5.0,0.02)
>>> print(t1)
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.  3.1 3.2 3.3 3.4 3.5
 3.6 3.7 3.8 3.9 4.  4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9]
>>> print(t2)
[0.   0.02 0.04 0.06 0.08 0.1  0.12 0.14 0.16 0.18 0.2  0.22 0.24 0.26
 0.28 0.3  0.32 0.34 0.36 0.38 0.4  0.42 0.44 0.46 0.48 0.5  0.52 0.54
 0.56 0.58 0.6  0.62 0.64 0.66 0.68 0.7  0.72 0.74 0.76 0.78 0.8  0.82
 0.84 0.86 0.88 0.9  0.92 0.94 0.96 0.98 1.   1.02 1.04 1.06 1.08 1.1
 1.12 1.14 1.16 1.18 1.2  1.22 1.24 1.26 1.28 1.3  1.32 1.34 1.36 1.38
 1.4  1.42 1.44 1.46 1.48 1.5  1.52 1.54 1.56 1.58 1.6  1.62 1.64 1.66
 1.68 1.7  1.72 1.74 1.76 1.78 1.8  1.82 1.84 1.86 1.88 1.9  1.92 1.94
 1.96 1.98 2.   2.02 2.04 2.06 2.08 2.1  2.12 2.14 2.16 2.18 2.2  2.22
 2.24 2.26 2.28 2.3  2.32 2.34 2.36 2.38 2.4  2.42 2.44 2.46 2.48 2.5
 2.52 2.54 2.56 2.58 2.6  2.62 2.64 2.66 2.68 2.7  2.72 2.74 2.76 2.78
 2.8  2.82 2.84 2.86 2.88 2.9  2.92 2.94 2.96 2.98 3.   3.02 3.04 3.06
 3.08 3.1  3.12 3.14 3.16 3.18 3.2  3.22 3.24 3.26 3.28 3.3  3.32 3.34
 3.36 3.38 3.4  3.42 3.44 3.46 3.48 3.5  3.52 3.54 3.56 3.58 3.6  3.62
 3.64 3.66 3.68 3.7  3.72 3.74 3.76 3.78 3.8  3.82 3.84 3.86 3.88 3.9
 3.92 3.94 3.96 3.98 4.   4.02 4.04 4.06 4.08 4.1  4.12 4.14 4.16 4.18
 4.2  4.22 4.24 4.26 4.28 4.3  4.32 4.34 4.36 4.38 4.4  4.42 4.44 4.46
 4.48 4.5  4.52 4.54 4.56 4.58 4.6  4.62 4.64 4.66 4.68 4.7  4.72 4.74
 4.76 4.78 4.8  4.82 4.84 4.86 4.88 4.9  4.92 4.94 4.96 4.98]
>>>
>>> print(f(t1))
[ 1.          0.73202885  0.25300172 -0.22892542 -0.54230031 -0.60653066
 -0.44399794 -0.1534533   0.13885029  0.32892176  0.36787944  0.26929836
  0.09307413 -0.08421696 -0.19950113 -0.22313016 -0.16333771 -0.05645231
  0.05108017  0.12100355  0.13533528  0.09906933  0.03424006 -0.03098169
 -0.07339237 -0.082085   -0.06008859 -0.02076765  0.01879134  0.04451472
  0.04978707  0.03644557  0.01259621 -0.01139753 -0.02699954 -0.03019738
 -0.02210536 -0.00763999  0.00691295  0.01637605  0.01831564  0.01340758
  0.00463389 -0.00419292 -0.00993258 -0.011109   -0.00813211 -0.0028106
  0.00254313  0.00602441]
>>> print(f(t2))
[ 1.00000000e+00  9.72469514e-01  9.30604472e-01  8.75630519e-01
  8.08933021e-01  7.32028848e-01  6.46537173e-01  5.54149795e-01
  4.56601475e-01  3.55640759e-01  2.53001717e-01  1.50377027e-01
  4.93927721e-02 -4.84147297e-02 -1.41619751e-01 -2.28925420e-01
 -3.09179223e-01 -3.81385611e-01 -4.44715627e-01 -4.98513513e-01
 -5.42300309e-01 -5.75774517e-01 -5.98809920e-01 -6.11450709e-01
 -6.13904100e-01 -6.06530660e-01 -5.89832576e-01 -5.64440144e-01
 -5.31096756e-01 -4.90642679e-01 -4.43997940e-01 -3.92144618e-01
 -3.36108841e-01 -2.76942794e-01 -2.15707024e-01 -1.53453298e-01
 -9.12082776e-02 -2.99582306e-02  2.93650179e-02  8.58967210e-02
  1.38850286e-01  1.87526678e-01  2.31322066e-01  2.69733663e-01
  3.02363730e-01  3.28921764e-01  3.49224898e-01  3.63196576e-01
  3.70863602e-01  3.72351659e-01  3.67879441e-01  3.57751541e-01
  3.42350253e-01  3.22126466e-01  2.97589828e-01  2.69298364e-01
  2.37847734e-01  2.03860317e-01  1.67974296e-01  1.30832924e-01
  9.30741301e-02  5.53206168e-02  1.81705854e-02 -1.78107837e-02
 -5.20989949e-02 -8.42169556e-02 -1.13740680e-01 -1.40303925e-01
 -1.63601736e-01 -1.83392873e-01 -1.99501135e-01 -2.11815608e-01
 -2.20289859e-01 -2.24940145e-01 -2.25842697e-01 -2.23130160e-01
 -2.16987278e-01 -2.07645925e-01 -1.95379578e-01 -1.80497354e-01
 -1.63337714e-01 -1.44261943e-01 -1.23647532e-01 -1.01881560e-01
 -7.93541795e-02 -5.64523135e-02 -3.35536502e-02 -1.10210171e-02
  1.08027864e-02  3.15996377e-02  5.10801656e-02  6.89872094e-02
  8.50986324e-02  9.92294691e-02  1.11233400e-01  1.21003555e-01
  1.28472660e-01  1.33612553e-01  1.36433095e-01  1.36980520e-01
  1.35335283e-01  1.31609437e-01  1.25943620e-01  1.18503704e-01
  1.09477179e-01  9.90693315e-02  8.74992915e-02  7.49960195e-02
  6.17942900e-02  4.81307428e-02  3.42400590e-02  2.03513176e-02
  6.68458480e-03 -6.55222115e-03 -1.91661491e-02 -3.09816865e-02
 -4.18428577e-02 -5.16149297e-02 -6.01857154e-02 -6.74664675e-02
 -7.33923659e-02 -7.79226074e-02 -8.10401102e-02 -8.27508549e-02
 -8.30828852e-02 -8.20849986e-02 -7.98251587e-02 -7.63886668e-02
 -7.18761299e-02 -6.64012659e-02 -6.00885870e-02 -5.30710030e-02
 -4.54873852e-02 -3.74801315e-02 -2.91927712e-02 -2.07676456e-02
 -1.23436981e-02 -4.05440563e-03  3.97412302e-03  1.16248571e-02
  1.87913428e-02  2.53789761e-02  3.13060373e-02  3.65044817e-02
  4.09204810e-02  4.45147201e-02  4.72624505e-02  4.91533115e-02
  5.01909306e-02  5.03923172e-02  4.97870684e-02  4.84164062e-02
  4.63320685e-02  4.35950765e-02  4.02744036e-02  3.64455703e-02
  3.21891905e-02  2.75894937e-02  2.27328489e-02  1.77063108e-02
  1.25962138e-02  7.48683134e-03  2.45912132e-03 -2.41042746e-03
 -7.05083223e-03 -1.13975255e-02 -1.53931271e-02 -1.89880715e-02
 -2.21410873e-02 -2.48195263e-02 -2.69995426e-02 -2.86661253e-02
 -2.98129904e-02 -3.04423382e-02 -3.05644854e-02 -3.01973834e-02
 -2.93660348e-02 -2.81018201e-02 -2.64417505e-02 -2.44276606e-02
 -2.21053558e-02 -1.95237309e-02 -1.67338738e-02 -1.37881698e-02
 -1.07394204e-02 -7.63998984e-03 -4.54099275e-03 -1.49153248e-03
  1.46199815e-03  4.27654592e-03  6.91294868e-03  9.33640353e-03
  1.15168475e-02  1.34292483e-02  1.50538037e-02  1.63760504e-02
  1.73868839e-02  1.80824928e-02  1.84642115e-02  1.85382975e-02
  1.83156389e-02  1.78114004e-02  1.70446155e-02  1.60377324e-02
  1.48161251e-02  1.34075760e-02  1.18417414e-02  1.01496075e-02
  8.36294774e-03  6.51378771e-03  4.63388808e-03  2.75425133e-03
  9.04660177e-04 -8.86746705e-04 -2.59385622e-03 -4.19291532e-03
 -5.66281499e-03 -6.98532112e-03 -8.14525084e-03 -9.13059348e-03
 -9.93257663e-03 -1.05456781e-02 -1.09675863e-02 -1.11991104e-02
 -1.12440458e-02 -1.11089965e-02 -1.08031605e-02 -1.03380819e-02
 -9.72737640e-03 -8.98643413e-03 -8.13210594e-03 -7.18237922e-03
 -6.15604815e-03 -5.07238421e-03 -3.95081196e-03 -2.81059519e-03
 -1.67053788e-03 -5.48704134e-04  5.37839064e-04  1.57325332e-03
  2.54313170e-03  3.43467091e-03  4.23681143e-03  4.94034436e-03
  5.53798489e-03  6.02441225e-03  6.39627712e-03  6.65217733e-03
  6.79260381e-03  6.81985852e-03]
>>>
>>> t=np.cos(2*np.pi*t2)
>>> print(t)
[ 1.          0.9921147   0.96858316  0.92977649  0.87630668  0.80901699
  0.72896863  0.63742399  0.53582679  0.42577929  0.30901699  0.18738131
  0.06279052 -0.06279052 -0.18738131 -0.30901699 -0.42577929 -0.53582679
 -0.63742399 -0.72896863 -0.80901699 -0.87630668 -0.92977649 -0.96858316
 -0.9921147  -1.         -0.9921147  -0.96858316 -0.92977649 -0.87630668
 -0.80901699 -0.72896863 -0.63742399 -0.53582679 -0.42577929 -0.30901699
 -0.18738131 -0.06279052  0.06279052  0.18738131  0.30901699  0.42577929
  0.53582679  0.63742399  0.72896863  0.80901699  0.87630668  0.92977649
  0.96858316  0.9921147   1.          0.9921147   0.96858316  0.92977649
  0.87630668  0.80901699  0.72896863  0.63742399  0.53582679  0.42577929
  0.30901699  0.18738131  0.06279052 -0.06279052 -0.18738131 -0.30901699
 -0.42577929 -0.53582679 -0.63742399 -0.72896863 -0.80901699 -0.87630668
 -0.92977649 -0.96858316 -0.9921147  -1.         -0.9921147  -0.96858316
 -0.92977649 -0.87630668 -0.80901699 -0.72896863 -0.63742399 -0.53582679
 -0.42577929 -0.30901699 -0.18738131 -0.06279052  0.06279052  0.18738131
  0.30901699  0.42577929  0.53582679  0.63742399  0.72896863  0.80901699
  0.87630668  0.92977649  0.96858316  0.9921147   1.          0.9921147
  0.96858316  0.92977649  0.87630668  0.80901699  0.72896863  0.63742399
  0.53582679  0.42577929  0.30901699  0.18738131  0.06279052 -0.06279052
 -0.18738131 -0.30901699 -0.42577929 -0.53582679 -0.63742399 -0.72896863
 -0.80901699 -0.87630668 -0.92977649 -0.96858316 -0.9921147  -1.
 -0.9921147  -0.96858316 -0.92977649 -0.87630668 -0.80901699 -0.72896863
 -0.63742399 -0.53582679 -0.42577929 -0.30901699 -0.18738131 -0.06279052
  0.06279052  0.18738131  0.30901699  0.42577929  0.53582679  0.63742399
  0.72896863  0.80901699  0.87630668  0.92977649  0.96858316  0.9921147
  1.          0.9921147   0.96858316  0.92977649  0.87630668  0.80901699
  0.72896863  0.63742399  0.53582679  0.42577929  0.30901699  0.18738131
  0.06279052 -0.06279052 -0.18738131 -0.30901699 -0.42577929 -0.53582679
 -0.63742399 -0.72896863 -0.80901699 -0.87630668 -0.92977649 -0.96858316
 -0.9921147  -1.         -0.9921147  -0.96858316 -0.92977649 -0.87630668
 -0.80901699 -0.72896863 -0.63742399 -0.53582679 -0.42577929 -0.30901699
 -0.18738131 -0.06279052  0.06279052  0.18738131  0.30901699  0.42577929
  0.53582679  0.63742399  0.72896863  0.80901699  0.87630668  0.92977649
  0.96858316  0.9921147   1.          0.9921147   0.96858316  0.92977649
  0.87630668  0.80901699  0.72896863  0.63742399  0.53582679  0.42577929
  0.30901699  0.18738131  0.06279052 -0.06279052 -0.18738131 -0.30901699
 -0.42577929 -0.53582679 -0.63742399 -0.72896863 -0.80901699 -0.87630668
 -0.92977649 -0.96858316 -0.9921147  -1.         -0.9921147  -0.96858316
 -0.92977649 -0.87630668 -0.80901699 -0.72896863 -0.63742399 -0.53582679
 -0.42577929 -0.30901699 -0.18738131 -0.06279052  0.06279052  0.18738131
  0.30901699  0.42577929  0.53582679  0.63742399  0.72896863  0.80901699
  0.87630668  0.92977649  0.96858316  0.9921147 ]
>>>

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, plot_number where plot_number 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. 

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:

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.

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.

上面没看懂。

Working with text

The text() command can be used to add text in an arbitrary location, and the xlabel() , ylabel() and title() (opens new window)are used to add text in the indicated locations.

import matplotlib.pyplot as plt
import numpy as np

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

# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=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()

>>> mu,sigma=100,15
>>> x=mu+sigma*np.random.randn(10000)
>>> print(x)
[ 85.62511626 116.95058782 108.26508996 ...  97.0213488  120.94596356
  90.45489603]
>>>

All of the text() (opens new window)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() :

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

上面没看懂。

Using mathematical expressions in text

matplotlib accepts TeX equation expressions in any text expression. For example to write the expression (\sigma_i=15) in the title, you can write a TeX expression surrounded by dollar signs:

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

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. 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.

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 matplotlib.pyplot as plt
import numpy as np

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 (arrow tip) and xytext locations (text location) are in data coordinates. There are a variety of other coordinate systems one can choose.

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:

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

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

# 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.
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}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()

运行失败,看不懂代码。因为symlog,不知道怎么办运行成功。

"""
===============
Pyplot tutorial
===============

An introduction to the pyplot interface.

"""

###############################################################################
# Intro to pyplot
# ===============
#
# :mod:`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 :mod:`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*
# :ref:`part of a figure <figure_parts>`
# and not the strict mathematical term for more than one axis).
#
# .. note::
#
#    the pyplot API is generally less-flexible than the object-oriented API.
#    Most of the function calls you see here can also be called as methods
#    from an ``Axes`` object. We recommend browsing the tutorials and
#    examples to see how this works.
#
# Generating visualizations with pyplot is very quick:

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

###############################################################################
# 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
# :func:`~matplotlib.pyplot.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]``.
#
# :func:`~matplotlib.pyplot.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:

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

###############################################################################
# Formatting the style of your plot
# ---------------------------------
#
# 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

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()

###############################################################################
# See the :func:`~matplotlib.pyplot.plot` documentation for a complete
# list of line styles and format strings.  The
# :func:`~matplotlib.pyplot.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
# <http://www.numpy.org>`_ 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.

import numpy as np

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

###############################################################################
# .. _plotting-with-keywords:
#
# Plotting with keyword strings
# =============================
#
# There are some instances where you have data in a format that lets you
# access particular variables with strings. For example, with
# :class:`numpy.recarray` or :class:`pandas.DataFrame`.
#
# Matplotlib allows you provide such an object with
# the ``data`` keyword argument. If provided, then you may generate plots with
# the strings corresponding to these variables.

data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

###############################################################################
# .. _plotting-with-categorical-vars:
#
# Plotting with categorical variables
# ===================================
#
# It is also possible to create a plot using categorical variables.
# Matplotlib allows you to pass categorical variables directly to
# many plotting functions. For example:

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()

###############################################################################
# .. _controlling-line-properties:
#
# Controlling line properties
# ===========================
#
# Lines have many attributes that you can set: linewidth, dash style,
# antialiased, etc; see :class:`matplotlib.lines.Line2D`.  There are
# several 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::
#
#       line, = plt.plot(x, y, '-')
#       line.set_antialiased(False) # turn off antialiasing
#
# * Use the :func:`~matplotlib.pyplot.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::
#
#       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 :class:`~matplotlib.lines.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
# 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
# :func:`~matplotlib.pyplot.setp` function with a line or lines
# as argument
#
# .. sourcecode:: ipython
#
#     In [69]: lines = plt.plot([1, 2, 3])
#
#     In [70]: plt.setp(lines)
#       alpha: float
#       animated: [True | False]
#       antialiased or aa: [True | False]
#       ...snip
#
# .. _multiple-figs-axes:
#
#
# Working with multiple figures and axes
# ======================================
#
# MATLAB, and :mod:`~matplotlib.pyplot`, have the concept of the current
# figure and the current axes.  All plotting commands apply to the
# current axes.  The function :func:`~matplotlib.pyplot.gca` returns the
# current axes (a :class:`matplotlib.axes.Axes` instance), and
# :func:`~matplotlib.pyplot.gcf` returns the current figure
# (:class:`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.


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

###############################################################################
# The :func:`~matplotlib.pyplot.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
# :func:`~matplotlib.pyplot.subplot` command specifies ``numrows,
# numcols, plot_number`` where ``plot_number`` 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 :func:`~matplotlib.pyplot.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 :doc:`/gallery/subplots_axes_and_figures/axes_demo` for an example of
# placing axes manually and :doc:`/gallery/subplots_axes_and_figures/subplot_demo` for an
# example with lots of subplots.
#
#
# You can create multiple figures by using multiple
# :func:`~matplotlib.pyplot.figure` calls with an increasing figure
# number.  Of course, each figure can contain as many axes and subplots
# as your heart desires::
#
#     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 :func:`~matplotlib.pyplot.clf`
# and the current axes with :func:`~matplotlib.pyplot.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 :doc:`/tutorials/intermediate/artists`)
#
# 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
# :func:`~matplotlib.pyplot.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 :func:`~matplotlib.pyplot.close`
# is called.
#
# .. _working-with-text:
#
# Working with text
# =================
#
# The :func:`~matplotlib.pyplot.text` command can be used to add text in
# an arbitrary location, and the :func:`~matplotlib.pyplot.xlabel`,
# :func:`~matplotlib.pyplot.ylabel` and :func:`~matplotlib.pyplot.title`
# are used to add text in the indicated locations (see :doc:`/tutorials/text/text_intro`
# for a more detailed example)

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

# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=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()

###############################################################################
# All of the :func:`~matplotlib.pyplot.text` commands return an
# :class:`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 :func:`~matplotlib.pyplot.setp`::
#
#   t = plt.xlabel('my data', fontsize=14, color='red')
#
# These properties are covered in more detail in :doc:`/tutorials/text/text_props`.
#
#
# Using mathematical expressions in text
# --------------------------------------
#
# matplotlib accepts TeX equation expressions in any text expression.
# For example to write the expression :math:`\sigma_i=15` in the title,
# you can write a TeX expression surrounded by dollar signs::
#
#     plt.title(r'$\sigma_i=15$')
#
# 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
# :doc:`/tutorials/text/mathtext`.  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 :doc:`/tutorials/text/usetex`.
#
#
# Annotating text
# ---------------
#
# The uses of the basic :func:`~matplotlib.pyplot.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
# :func:`~matplotlib.pyplot.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.

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`` (arrow tip) and ``xytext``
# locations (text location) are in data coordinates.  There are a
# variety of other coordinate systems one can choose -- see
# :ref:`annotations-tutorial` and :ref:`plotting-guide-annotation` for
# details.  More examples can be found in
# :doc:`/gallery/text_labels_and_annotations/annotation_demo`.
#
#
# Logarithmic and other nonlinear axes
# ====================================
#
# :mod:`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:
#
#     plt.xscale('log')
#
# An example of four plots with the same data and different scales for the y axis
# is shown below.

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

# 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.
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}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()

###############################################################################
# It is also possible to add your own scale, see :ref:`adding-new-scales` for
# details.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值