The matplotlib library is specially used to develop 2D charts (including 3D charts), with outstanding advantages:
-
It is extremely simple to use.
-
Visualize data in a progressive, interactive way.
-
Expressions and text are typeset using LaTeX.
-
Strong control over image elements.
-
It can output various formats such as PNG, PDF, SVG and EPS.
Install
conda install matplotlib
or
pip install matplotlib
matplotlib architecture
One of the main tasks of matplotlib is to provide a set of functions and tools for representing and manipulating graphical objects (primary objects) and its internal objects. It not only handles graphics, but also provides event handling tools and the ability to add animation effects to graphics. With these additional features, matplotlib can generate interactive graphs of events triggered by keyboard key presses or mouse movements.
Logically speaking, the overall architecture of matplotlib is 3 layers, with one-way communication between layers:
-
Scripting layer.
-
Artist layer.
-
Backend layer.
1. Basic usage of matplotlib
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 30) # 在区间内生成30个等差数
y = np.sin(x)
print('x = ', x)
print('y = ', y)
output:
x = [-3.14159265 -2.92493109 -2.70826953 -2.49160797 -2.2749464 -2.05828484
-1.84162328 -1.62496172 -1.40830016 -1.19163859 -0.97497703 -0.75831547
-0.54165391 -0.32499234 -0.10833078 0.10833078 0.32499234 0.54165391
0.75831547 0.97497703 1.19163859 1.40830016 1.62496172 1.84162328
2.05828484 2.2749464 2.49160797 2.70826953 2.92493109 3.14159265]
y = [-1.22464680e-16 -2.14970440e-01 -4.19889102e-01 -6.05174215e-01
-7.62162055e-01 -8.83512044e-01 -9.63549993e-01 -9.98533414e-01
-9.86826523e-01 -9.28976720e-01 -8.27688998e-01 -6.87699459e-01
-5.15553857e-01 -3.19301530e-01 -1.08119018e-01 1.08119018e-01
3.19301530e-01 5.15553857e-01 6.87699459e-01 8.27688998e-01
9.28976720e-01 9.86826523e-01 9.98533414e-01 9.63549993e-01
8.83512044e-01 7.62162055e-01 6.05174215e-01 4.19889102e-01
2.14970440e-01 1.22464680e-16]
-
draw a curve
plt.figure() # 创建一个新的窗口
plt.plot(x, y) # 画一个x与y相关的曲线
plt.show()# 显示图像
-
Draw multiple curves and add axes and labels
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100) # 在区间内生成21个等差数
y = np.sin(x)
linear_y = 0.2 * x + 0.1
plt.figure(figsize = (8, 6)) # 自定义窗口的大小
plt.plot(x, y)
plt.plot(x, linear_y, color = "red", linestyle = '--') # 自定义颜色和表示方式
plt.title('y = sin(x) and y = 0.2x + 0.1') # 定义该曲线的标题
plt.xlabel('x') # 定义横轴标签
plt.ylabel('y') # 定义纵轴标签
plt.show()
-
Specify the coordinate range and set the axis scale
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100) # 在区间内生成21个等差数
y = np.sin(x)
linear_y = 0.2 * x + 0.1
plt.figure(figsize = (8, 6)) # 自定义窗口的大小
plt.plot(x, y)
plt.plot(x, linear_y, color = "red", linestyle = '--') # 自定义颜色和表示方式
plt.title('y = sin(x) and y = 0.2x + 0.1') # 定义该曲线的标题
plt.xlabel('x') # 定义横轴标签
plt.ylabel('y') # 定义纵轴标签
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1)
# 重新设置x轴的刻度
# plt.xticks(np.linspace(-np.pi, np.pi, 5))
x_value_range = np.linspace(-np.pi, np.pi, 5)
x_value_strs = [r'$\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$']
plt.xticks(x_value_range, x_value_strs)
plt.show() # 显示图像
-
Define the axes with the origin at the center
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100)
y = np.sin(x)
linear_y = 0.2 * x + 0.1
plt.figure(figsize = (8, 6))
plt.plot(x, y)
plt.plot(x, linear_y, color = "red", linestyle = '--')
plt.title('y = sin(x) and y = 0.2x + 0.1')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1)
# plt.xticks(np.linspace(-np.pi, np.pi, 5))
x_value_range = np.linspace(-np.pi, np.pi, 5)
x_value_strs = [r'$\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$']
plt.xticks(x_value_range, x_value_strs)
ax = plt.gca() # 获取坐标轴
ax.spines['right'].set_color('none') # 隐藏上方和右方的坐标轴
ax.spines['top'].set_color('none')
# 设置左方和下方坐标轴的位置
ax.spines['bottom'].set_position(('data', 0)) # 将下方的坐标轴设置到y = 0的位置
ax.spines['left'].set_position(('data', 0)) # 将左方的坐标轴设置到 x = 0 的位置
plt.show() # 显示图像
-
legend legend
Replace the axis labels with the xticks() and yticks() functions, passing in two columns of values for each function. The first list stores the positions of the ticks, and the second list stores the labels of the ticks. import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100)
y = np.sin(x)
linear_y = 0.2 * x + 0.1
plt.figure(figsize = (8, 6))
# 为曲线加上标签
plt.plot(x, y, label = "y = sin(x)")
plt.plot(x, linear_y, color = "red", linestyle = '--', label = 'y = 0.2x + 0.1')
plt.title('y = sin(x) and y = 0.2x + 0.1')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1)
# plt.xticks(np.linspace(-np.pi, np.pi, 5))
x_value_range = np.linspace(-np.pi, np.pi, 5)
x_value_strs = [r'$\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$']
plt.xticks(x_value_range, x_value_strs)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# 将曲线的信息标识出来
plt.legend(loc = 'lower right', fontsize = 12)
plt.show()
Optional settings for the loc parameter in the legend method
location string | position number | position statement |
---|---|---|
‘best’ | 0 | Best location |
‘upper right’ | 1 | top right |
‘upper left’ | 2 | top left |
‘lower left’ | 3 | bottom left |
‘lower right’ | 4 | bottom right |
‘right’ | 5 | Right |
‘center left’ | 6 | Vertically Centered Left |
‘center right’ | 7 | Right vertical center |
‘lower center’ | 8 | Bottom horizontally centered |
‘upper center’ | 9 | Top horizontally centered |
‘center’ | 10 | The middle |
2. Histogram
Method used: plt.bar
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize = (16, 12))
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([3, 5, 7, 6, 2, 6, 10, 15])
plt.plot(x, y, 'r', lw = 5) # 指定线的颜色和宽度
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([13, 25, 17, 36, 21, 16, 10, 15])
plt.bar(x, y, 0.2, alpha = 1, color='b') # 生成柱状图,指明图的宽度,透明度和颜色
plt.show()
Sometimes the histogram will appear on both sides of the x-axis for easy comparison. The code is implemented as follows:
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize = (16, 12))
n = 12
x = np.arange(n) # 按顺序生成从12以内的数字
y1 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)
y2 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)
# 设置柱状图的颜色以及边界颜色
#+y表示在x轴的上方 -y表示在x轴的下方
plt.bar(x, +y1, facecolor = '#9999ff', edgecolor = 'white')
plt.bar(x, -y2, facecolor = '#ff9999', edgecolor = 'white')
plt.xlim(-0.5, n) # 设置x轴的范围,
plt.xticks(()) # 可以通过设置刻度为空,消除刻度
plt.ylim(-1.25, 1.25) # 设置y轴的范围
plt.yticks(())
# plt.text()在图像中写入文本,设置位置,设置文本,ha设置水平方向对其方式,va设置垂直方向对齐方式
for x1, y in zip(x, y2):
plt.text(x1, -y - 0.05, '%.2f' % y, ha = 'center', va = 'top')
for x1, y in zip(x, y1):
plt.text(x1, y + 0.05, '%.2f' % y, ha = 'center', va = 'bottom')
plt.show()
3. Scatter plot
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2
plt.scatter(x, y, s = area,c = colors, alpha = 0.8)
plt.show()
Four, contour map
import matplotlib.pyplot as plt
import numpy as np
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y) # 生成网格坐标 将x轴与y轴正方形区域的点全部获取
line_num = 10 # 等高线的数量
plt.figure(figsize = (16, 12))
#contour 生成等高线的函数
#前俩个参数表示点的坐标,第三个参数表示等成等高线的函数,第四个参数表示生成多少个等高线
C = plt.contour(X, Y, f(X, Y), line_num, colors = 'black', linewidths = 0.5) # 设置颜色和线段的宽度
plt.clabel(C, inline = True, fontsize = 12) # 得到每条等高线确切的值
# 填充颜色, cmap 表示以什么方式填充,hot表示填充热量的颜色
plt.contourf(X, Y, f(X, Y), line_num, alpha = 0.75, cmap = plt.cm.hot)
plt.show()
Five, processing pictures
import matplotlib.pyplot as plt
import matplotlib.image as mpimg # 导入处理图片的库
import matplotlib.cm as cm # 导入处理颜色的库colormap
plt.figure(figsize = (16, 12))
img = mpimg.imread('image/fuli.jpg')# 读取图片
print(img) # numpy数据
print(img.shape) #
plt.imshow(img, cmap = 'hot')
plt.colorbar() # 得到颜色多对应的数值
plt.show()
[[[ 11 23 63]
[ 12 24 64]
[ 1 13 55]
...
[ 1 12 42]
[ 1 12 42]
[ 1 12 42]]
[[ 19 31 71]
[ 3 15 55]
[ 0 10 52]
...
[ 0 11 39]
[ 0 11 39]
[ 0 11 39]]
[[ 22 34 74]
[ 3 15 55]
[ 7 19 61]
...
[ 0 11 39]
[ 0 11 39]
[ 0 11 39]]
...
[[ 84 125 217]
[ 80 121 213]
[ 78 118 214]
...
[ 58 90 191]
[ 54 86 187]
[ 53 85 186]]
[[ 84 124 220]
[ 79 119 215]
[ 78 117 218]
...
[ 55 87 188]
[ 55 87 188]
[ 55 87 188]]
[[ 83 121 220]
[ 80 118 219]
[ 83 120 224]
...
[ 56 88 189]
[ 58 90 191]
[ 59 91 192]]]
(728, 516, 3)
Use numpy matrix to get pictures
import matplotlib.pyplot as plt
import matplotlib.cm as cm # 导入处理颜色的库colormap
import numpy as np
size = 8
# 得到一个8*8数值在(0, 1)之间的矩阵
a = np.linspace(0, 1, size ** 2).reshape(size, size)
plt.figure(figsize = (16, 12))
plt.imshow(a)
plt.show()
6. 3D map
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # 导入Axes3D对象
fig = plt.figure(figsize = (16, 12))
ax = fig.add_subplot(111, projection = '3d') # 得到3d图像
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y) # 生成网格
Z = np.sqrt(X ** 2 + Y ** 2)
# 画曲面图 # 行和列对应的跨度 # 设置颜色
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = plt.get_cmap('rainbow'))
plt.show()
The above is the data visualization of matplotlib based on test data. Combined with the data in the actual project, the code can be slightly modified to have impressive effects.