文章目录
1. 线图(line plot)
plot()
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt, subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') # 设置x,y轴标签和图形标题
ax.grid() # 开启网格
fig.savefig("test.png") # 保存图片
plt.show()
多子图(Multiple subplots)
subplot()
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1) # 等价于plt.subplot(211)
plt.plot(x1, y1, 'o-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2) # 等价于plt.subplot(212)
plt.plot(x2, y2, '.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
2. 图片(Images)
imshow()
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.path import Path
from matplotlib.patches import PathPatch
# 加载上面保存的test.png图片
with cbook.get_sample_data(r'C:\Users\sjl\my_jupyter_notebook\my_matplotlib\test.png') as image_file:
image = plt.imread(image_file)
fig, ax = plt.subplots()
ax.imshow(image)
ax.axis('off') # 清除x-axis和y-axis
# w, h = 512, 512
# with cbook.get_sample_data('ct.raw.gz') as datafile:
# s = datafile.read()
# A = np.frombuffer(s, np.uint16).astype(float).reshape(w, h))
# A /= A.max()
#
# fig, ax = plt.subplots()
# extent = (0, 25, 0, 25)
# im = ax.imshow(A, cmap=plt.cm.hot, origin='upper', # extent=extent)
#
# markers = [(15.9, 14.5), (16.8, 15)]
# x, y = zip(*markers)
# ax.plot(x, y, 'o')
#
# ax.set_title('CT density')
plt.show()
3. 轮廓和伪色(Contouring and pseudocolor)
pcolormesh()和contour()
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import numpy as np
dx, dy = 0.05, 0.05
y, x = np.mgrid[slice(1, 5 + dy, dy), slice(1, 5 + dx, dx)]
z = np.sin(x) ** 10 + np.cos(10 + y*x) * np.cos(x)
z = z[:-1, :-1]
levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max()) # 刻度的最大间隔数量为15,刻度的上下限位z.min()和z.max()
cmap = plt.get_cmap('PiYG')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) # 根据离散间隔生成颜色图索引
fig, (ax0, ax1) = plt.subplots(nrows=2)
im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=norm)
fig.colorbar(im, ax=ax0)
ax0.set_title('pcolormesh with levels')
cf = ax1.contour(x[:-1, :-1] + dx/2., y[:-1, :-1] + dy/2., z, levels=levels, cmap=cmap)
fig.colorbar(cf, ax=ax1)
ax1.set_title('contour with levels')
fig.tight_layout()
plt.show()
4. 直方图(Histograms)
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
mu = 100 # 分布的均值
sigma = 15 # 分布的标准差
x = mu + sigma * np.random.randn(437)
num_bins = 50
fig, ax = plt.subplots()
n, bins, patches = ax.hist(x, num_bins, density=1) # 直方图的数据
# 添加一条拟合线
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 /sigma * (bins - mu)) ** 2))
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
fig.tight_layout() # 调整间距以防止截断ylabel
plt.show()
5. 路径图(Path)
import matplotlib.path as mpath # matplotlib中处理折线的模块
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
Path = mpath.Path
path_data = [
(Path.MOVETO, (1.58, -2.57)), # (顶点类型,顶点坐标)
(Path.CURVE4, (0.35, -1.1)),
(Path.CURVE4, (-1.75, 2.0)),
(Path.CURVE4, (0.375, 2.0)),
(Path.LINETO, (0.85, 1.15)),
(Path.CURVE4, (2.2, 3.2)),
(Path.CURVE4, (3, 0.05)),
(Path.CURVE4, (2.0, -0.5)),
(Path.CLOSEPOLY, (1.58, -2.57)),
]
codes, verts = zip(*path_data) # 定点类型, 顶点
path = mpath.Path(verts, codes) # 创建路径
patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
ax.add_patch(patch)
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')
ax.grid()
ax.axis('equal')
plt.show()
6. 3D表面(颜色图)(3D surface (color map))
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# 造数据
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2, Y**2)
Z = np.sin(R)
# 绘制surface
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
# 自定义z轴
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# 添加颜色条
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()