Installation and Python Visualization --Matplotlib pyplot

Matplotlib is used in a Python drawing 2D graphics library array. Although it originated in imitation of MATLAB graphics commands, but it is independent of MATLAB, it can be used to Pythonic and object-oriented way. Although Matplotlib mainly written in pure Python, but it is extensive use of NumPy and other extension code, even for large arrays can provide good performance.

1. Install

There are many different ways to install matplotlib, the simplest way is to use pip.

pip install matplotlib

2. pyplot

matplotlib.pyplotIs a mechanism for collection of command-style function, so matplotlib more like MATLAB. Each graphics drawing function of some changes: e.g., create graphics, to create the drawing area in the drawing, draw some lines in the drawing area, decorative labels using the drawing and the like. In matplotlib.pyplotthe various states saved across function calls, in order to track such things as the current pattern and the like of the drawing area, and drawing functions always point to the current axis domain.

Note: This document and in most locations in the "axis domain" (axes) refers to the (area surrounded by two axes) portion of a graphic, rather than strict mathematical terms to refer to more than one axis.

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4])
plt.ylabel('numbers')
plt.show()

Here Insert Picture Description

You may wonder why the xrange of the axis is 0-3, ythe range of the shaft 1-4. If you to plot()provide a single list or array command, matplotlibit assumes it is a ysequence of values, and you automatically generated xvalue. Since python range from 0, the default xvector has the ysame length, but zero. So xdata [0,1,2,3].

plot()It is a general command, and accepts any number of parameters. For example, to draw xand y, you can execute the command:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.ylabel('numbers')
plt.show()

Here Insert Picture Description

For each x,yparameter, there is an optional third parameter, which is indicative of color and line type of graphics format string. Format string of letters and symbols from MATLAB, and the color string together with a linear string. The default format for the string "b-", which is a solid blue line. For example, to draw a red circle above, you need to perform:

import matplotlib.pyplot as plt

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

Here Insert Picture Description

For a complete list of linear and format strings, see the plot () documentation . Examples of the axis()reception command [xmin,xmax,ymin,ymax]list, and specify the viewable area of the shaft domain.

matplotlib accepts the following format string of characters or marks to control the line style:

character description character description
'-' solid line '--' dotted line
'-.' Dotted line ':' The dotted line
'.' point ',' Pixels
'o' Circles 'v' Lower triangular
'^' The triangle '<' Left Triangle
'>' Right Triangle '1' 1 plus lower triangular
'2' 1 plus Triangle '3' 1 of the left triangle
'4' 1 month right triangle 's' square
'p' Pentagon '*' Star
'h' Hexagonal 1 'H' Hexagonal 2
'+' plus 'x' Multiplication sign
'D' diamond 'd' diamond
'|' Vertical line '_' Level

matplotlib Color supports the following abbreviations:

character colour character colour character colour
‘b’ blue ‘g’ green ‘r’ red
‘c’ Blue color ‘m’ Magenta 'Y' yellow
‘k’ black ‘w’ white

If you matplotlibonly use the list, it is for the digital processing is quite useless. In general, you can use numpyarrays. In fact, all sequences are converted within the numpyarray. The following example demonstrates the use of different formats and string arrays, a plurality of bars drawn in a single command.

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

Here Insert Picture Description

3. Control Line Properties

There are many lines you can set the property: linewidth, dash style, antialiasedand so on, see matplotlib.lines.Line2D. There are several ways to set attribute:

  • Use keyword arguments:
plt.plot(x, y, linewidth=2.0)
  • Use Line2Dinstance settermethods. plotReturns Line2Da list of objects, for example line1,line2 = plot(x1,y1,x2,y2). In the following code, we assume that only one line, a length of the list is returned. We linedeconstructing a tuple, get the first element of the list:
line, = plt.plot(x, y, '-')
line.set_antialiased(False) # turn off antialising
  • Use setp()command. The following example uses MATLAB style commands to set a plurality of lines on the list of attributes. setpSingle objects using the object list or work transparently. You can use python string parameter keywords or MATLAB style / value pairs:
lines = plt.plot(x1, y1, x2, y2)
# 使用关键字参数
plt.setp(lines, color='r', linewidth=2.0)
# 或者 MATLAB 风格的字符串值对
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

The following properties are available Line2D:

Attributes Value Type
alpha Floating-point values
animated [True / False]
antialiased or aa [True / False]
clip_box matplotlib.transform.Bbox examples
clip_on [True / False]
clip_path Path example, Transform, and examples Patch
color or c Matplotlib any color
contains Hit test function
dash_capstyle [‘butt’ / ‘round’ / ‘projecting’]
dash_joinstyle [‘miter’ / ‘round’ / ‘bevel’]
dashes In points of connection / disconnection sequence Ink
data (np.array xdata, np.array ydata)
figure matplotlib.figure.Figure examples
label Any string
linestyle or ls [ ‘-’ / ‘–’ / ‘-.’ / ‘:’ / ‘steps’ / …]
linewidth or lw In points floating point value
lod [True / False]
marker [ ‘+’ / ‘,’ / ‘.’ / ‘1’ / ‘2’ / ‘3’ / ‘4’ ]
markeredgecolor or mec Matplotlib any color
markeredgewidth or mew In points floating point value
markerfacecolor or mfc Matplotlib any color
markersize or ms 浮点值
markevery [ None / 整数值 / (startind, stride) ]
picker 用于交互式线条选择
pickradius 线条的拾取选择半径
solid_capstyle [‘butt’ / ‘round’ / ‘projecting’]
solid_joinstyle [‘miter’ / ‘round’ / ‘bevel’]
transform matplotlib.transforms.Transform 实例
visible [True / False]
xdata np.array
ydata np.array
zorder 任何数值

4. 处理多个图形和轴域

MATLAB 和 pyplot 具有当前图形和当前轴域的概念。 所有绘图命令适用于当前轴域。 函数gca()返回当前轴域(一个matplotlib.axes.Axes实例),gcf()返回当前图形(matplotlib.figure.Figure实例)。 通常,你不必担心这一点,因为它都是在幕后处理。 下面是一个创建两个子图的脚本。

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

Here Insert Picture Description

这里的figure()命令是可选的,因为默认情况下将创建figure(1),如果不手动指定任何轴域,则默认创建subplot(111)subplot()命令指定numrowsnumcolsfignum,其中fignum的范围是从1numrows * numcols。 如果numrows * numcols <10,则subplot命令中的逗号是可选的。 因此,子图subplot(211)subplot(2, 1, 1)相同。 你可以创建任意数量的子图和轴域。

如果要手动放置轴域,即不在矩形网格上,请使用axes()命令,该命令允许你将axes([left, bottom, width, height])指定为位置,其中所有值都使用小数(0 到 1)坐标。 手动放置轴域的示例请参见pylab_examples示例代码:axes_demo.py,具有大量子图的示例请参见pylab_examples示例代码:subplots_demo.py

你可以通过使用递增图形编号多次调用figure()来创建多个图形。 当然,每个数字可以包含所需的轴和子图数量:

import matplotlib.pyplot as plt

plt.figure(1)  # 第一个图形
plt.subplot(211)  # 第一个图形的第一个子图
plt.plot([1, 2, 3])
plt.subplot(212)  # 第一个图形的第二个子图
plt.plot([4, 5, 6])

plt.figure(2)  # 第二个图形
plt.plot([4, 5, 6])  # 默认创建 subplot(111)

plt.show()

你可以使用clf()清除当前图形,使用cla()清除当前轴域。 如果你搞不清在幕后维护的状态(特别是当前的图形和轴域),不要绝望:这只是一个面向对象的 API 的简单的状态包装器,你可以使用面向对象 API(见艺术家教程)。

如果你正在制作大量的图形,你需要注意一件事:在一个图形用close()显式关闭之前,该图所需的内存不会完全释放。 删除对图形的所有引用,和/或使用窗口管理器杀死屏幕上出现的图形的窗口是不够的,因为在调用close()之前,pyplot会维护内部引用。

5. 处理文本

text()命令可用于在任意位置添加文本,xlabel()ylabel()title()用于在指定的位置添加文本(详细示例请参阅文本介绍)。

import numpy as np
import matplotlib.pyplot as plt

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

# 数据的直方图
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()

Here Insert Picture Description

所有的text()命令返回一个matplotlib.text.Text实例。 与上面一样,你可以通过将关键字参数传递到text函数或使用setp()来自定义属性:

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

这些属性的更详细介绍请见文本属性和布局

6. 在文本中使用数学表达式

matplotlib在任何文本表达式中接受 TeX 方程表达式。 例如,要在标题中写入表达式,可以编写一个由美元符号包围的 TeX 表达式:

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

标题字符串之前的r很重要 - 它表示该字符串是一个原始字符串,而不是将反斜杠作为 python 转义处理。 matplotlib有一个内置的 TeX 表达式解析器和布局引擎,并且自带了自己的数学字体 - 详细信息请参阅编写数学表达式。 因此,你可以跨平台使用数学文本,而无需安装 TeX。 对于安装了 LaTeX 和dvipng的用户,还可以使用 LaTeX 格式化文本,并将输出直接合并到显示图形或保存的 postscript 中 - 请参阅使用 LaTeX 进行文本渲染

7. 标注文本

上面的text()基本命令将文本放置在轴域的任意位置。 文本的一个常见用法是对图的某些特征执行标注,而annotate()方法提供一些辅助功能,使标注变得容易。 在标注中,有两个要考虑的点:由参数xy表示的标注位置和xytext表示的文本位置。 这两个参数都是(x, y)元组。

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2 * np.pi * t)
line, = ax.plot(t, s, lw=2)

ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )
ax.set_ylim(-2, 2)
plt.show()

Here Insert Picture Description

在此基本示例中,xy(箭头提示)和xytext(文本)都位于数据坐标中。 有多种其他坐标系可供选择 - 详细信息请参阅标注文本标注轴域。 更多示例可以在pylab_examples示例代码:annotation_demo.py中找到。

8. 对数和其它非线性轴

matplotlib.pyplotNot only supports linear axis scale, also supports logarithmic and logarithmic scale. If the data across many orders of magnitude, often using it. Change the axis scale is easy:

plt.xscale('log')

The following example shows four graphs, and data having different scales of the same yaxis.

import numpy as np
import matplotlib.pyplot as plt

# 生成一些区间 [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
plt.figure(1)

# 线性
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)

# 对数
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)

# 对称的对数
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.05)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)

plt.show()

Here Insert Picture Description

You can also add your own scale, more information, see Add a new scale and projection to matplotlib .

Published 66 original articles · won praise 101 · views 30000 +

Guess you like

Origin blog.csdn.net/u010705932/article/details/104456888