Matplotlib 二维数据与统计图函数
用于二维数据展示和统计分布可视化的函数。
函数一览
| 函数 | 功能 |
|---|---|
| hist2d() | 二维直方图 |
| hexbin() | 六边形分箱图(Hexbin) |
| stairs() | 阶梯直方图(替代 hist 的 step 模式) |
| matshow() | 在新 Figure 中显示矩阵 |
| pcolor() | 伪彩色图(PolyCollection) |
| pcolormesh() | 伪彩色图(QuadMesh,性能更好) |
| spy() | 稀疏矩阵非零元素图案 |
| figimage() | 在 Figure 级别放置图像 |
| ecdf() | 经验累积分布函数 |
| violinplot() | 小提琴图 |
hist2d() - 二维直方图
matplotlib.pyplot.hist2d(x, y, bins=10, range=None, density=False,
weights=None, cmin=None, cmax=None, *, **kwargs)
实例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
x = np.random.randn(5000)
y = x * 0.5 + np.random.randn(5000) * 0.5
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
layout='constrained')
# 二维直方图
h, xedges, yedges, im = ax1.hist2d(x, y, bins=40, cmap='Blues')
fig.colorbar(im, ax=ax1, label='Count')
ax1.set_title('hist2d()')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
# 六边形分箱
hb = ax2.hexbin(x, y, gridsize=30, cmap='YlOrRd')
fig.colorbar(hb, ax=ax2, label='Count')
ax2.set_title('hexbin()')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
plt.show()
import numpy as np
np.random.seed(42)
x = np.random.randn(5000)
y = x * 0.5 + np.random.randn(5000) * 0.5
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
layout='constrained')
# 二维直方图
h, xedges, yedges, im = ax1.hist2d(x, y, bins=40, cmap='Blues')
fig.colorbar(im, ax=ax1, label='Count')
ax1.set_title('hist2d()')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
# 六边形分箱
hb = ax2.hexbin(x, y, gridsize=30, cmap='YlOrRd')
fig.colorbar(hb, ax=ax2, label='Count')
ax2.set_title('hexbin()')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
plt.show()
stairs() - 阶梯直方图
matplotlib.pyplot.stairs(values, edges=None, *, orientation='vertical',
baseline=0, fill=False, **kwargs)
实例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
data = np.random.randn(500)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# hist + stairs 对比
counts, bins = np.histogram(data, bins=30)
ax1.hist(data, bins=30, alpha=0.3, color='steelblue')
ax1.stairs(counts, bins, fill=False, color='red',
linewidth=2, label='stairs outline')
ax1.set_title('stairs() outline on hist()')
ax1.legend()
# fill=True 的 stairs
ax2.stairs(counts, bins, fill=True, color='coral',
alpha=0.7, edgecolor='black', linewidth=1)
ax2.set_title('stairs() with fill=True')
plt.show()
import numpy as np
np.random.seed(42)
data = np.random.randn(500)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# hist + stairs 对比
counts, bins = np.histogram(data, bins=30)
ax1.hist(data, bins=30, alpha=0.3, color='steelblue')
ax1.stairs(counts, bins, fill=False, color='red',
linewidth=2, label='stairs outline')
ax1.set_title('stairs() outline on hist()')
ax1.legend()
# fill=True 的 stairs
ax2.stairs(counts, bins, fill=True, color='coral',
alpha=0.7, edgecolor='black', linewidth=1)
ax2.set_title('stairs() with fill=True')
plt.show()
pcolormesh() - 伪彩色图
matplotlib.pyplot.pcolormesh(*args, alpha=None, norm=None,
cmap=None, vmin=None, vmax=None, shading=None, **kwargs)
实例
import matplotlib.pyplot as plt
import numpy as np
# 创建二维数据
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
layout='constrained')
# pcolormesh - 默认 shading='flat'(丢最后一行/列)
pc1 = ax1.pcolormesh(X, Y, Z, cmap='RdYlBu',
shading='auto')
fig.colorbar(pc1, ax=ax1, label='Value')
ax1.set_title('pcolormesh()')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
# pcolor - 渲染为 PolyCollection
pc2 = ax2.pcolor(X, Y, Z, cmap='RdYlBu')
fig.colorbar(pc2, ax=ax2, label='Value')
ax2.set_title('pcolor()')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
plt.show()
import numpy as np
# 创建二维数据
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
layout='constrained')
# pcolormesh - 默认 shading='flat'(丢最后一行/列)
pc1 = ax1.pcolormesh(X, Y, Z, cmap='RdYlBu',
shading='auto')
fig.colorbar(pc1, ax=ax1, label='Value')
ax1.set_title('pcolormesh()')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
# pcolor - 渲染为 PolyCollection
pc2 = ax2.pcolor(X, Y, Z, cmap='RdYlBu')
fig.colorbar(pc2, ax=ax2, label='Value')
ax2.set_title('pcolor()')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
plt.show()
spy() - 稀疏矩阵图案
matplotlib.pyplot.spy(Z, precision=0, marker=None, markersize=None,
aspect='equal', origin='upper', **kwargs)
实例
import matplotlib.pyplot as plt
import numpy as np
from scipy import sparse
# 创建稀疏矩阵
np.random.seed(42)
dense = np.random.rand(50, 50)
dense[dense < 0.9] = 0 # 90% 为零
sparse_mat = sparse.csr_matrix(dense)
fig, ax = plt.subplots(figsize=(5, 5), layout='constrained')
ax.spy(sparse_mat, markersize=5, color='steelblue')
ax.set_title('spy() - Sparse Matrix Pattern')
plt.show()
import numpy as np
from scipy import sparse
# 创建稀疏矩阵
np.random.seed(42)
dense = np.random.rand(50, 50)
dense[dense < 0.9] = 0 # 90% 为零
sparse_mat = sparse.csr_matrix(dense)
fig, ax = plt.subplots(figsize=(5, 5), layout='constrained')
ax.spy(sparse_mat, markersize=5, color='steelblue')
ax.set_title('spy() - Sparse Matrix Pattern')
plt.show()
matshow() / figimage()
matplotlib.pyplot.matshow(A, fignum=None, **kwargs)
matplotlib.pyplot.figimage(X, xo=0, yo=0, alpha=None, norm=None,
cmap=None, vmin=None, vmax=None, origin=None, **kwargs)
实例
import matplotlib.pyplot as plt
import numpy as np
# matshow - 自动创建新 Figure 显示矩阵
matrix = np.random.rand(8, 8)
plt.matshow(matrix, cmap='viridis')
plt.title('matshow()')
plt.colorbar(label='Value')
plt.show()
print("runoob: matshow displayed")
import numpy as np
# matshow - 自动创建新 Figure 显示矩阵
matrix = np.random.rand(8, 8)
plt.matshow(matrix, cmap='viridis')
plt.title('matshow()')
plt.colorbar(label='Value')
plt.show()
print("runoob: matshow displayed")
ecdf() - 经验累积分布
matplotlib.pyplot.ecdf(x, *, ax=None, complementary=False,
**kwargs)
实例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
data1 = np.random.normal(0, 1, 200)
data2 = np.random.normal(2, 0.5, 200)
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
ax.ecdf(data1, label='N(0, 1)')
ax.ecdf(data2, label='N(2, 0.5)')
ax.set_title('ecdf() - Empirical CDF')
ax.set_xlabel('Value')
ax.set_ylabel('Cumulative Probability')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
import numpy as np
np.random.seed(42)
data1 = np.random.normal(0, 1, 200)
data2 = np.random.normal(2, 0.5, 200)
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
ax.ecdf(data1, label='N(0, 1)')
ax.ecdf(data2, label='N(2, 0.5)')
ax.set_title('ecdf() - Empirical CDF')
ax.set_xlabel('Value')
ax.set_ylabel('Cumulative Probability')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
violinplot() - 小提琴图
matplotlib.pyplot.violinplot(dataset, positions=None, vert=True,
widths=0.5, showmeans=False, showmedians=False,
showextrema=True, **kwargs)
实例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
data = [
np.random.normal(0, 1, 200),
np.random.normal(2, 1.5, 200),
np.random.gamma(2, 1, 200),
]
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
vp = ax.violinplot(data, showmeans=True, showmedians=True)
# 自定义颜色
colors = ['#3498db', '#e74c3c', '#2ecc71']
for body, color in zip(vp['bodies'], colors):
body.set_facecolor(color)
body.set_alpha(0.7)
ax.set_title('violinplot()')
ax.set_xticks([1, 2, 3])
ax.set_xticklabels(['Normal', 'Normal(wide)', 'Gamma'])
ax.grid(axis='y', alpha=0.3)
plt.show()
import numpy as np
np.random.seed(42)
data = [
np.random.normal(0, 1, 200),
np.random.normal(2, 1.5, 200),
np.random.gamma(2, 1, 200),
]
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
vp = ax.violinplot(data, showmeans=True, showmedians=True)
# 自定义颜色
colors = ['#3498db', '#e74c3c', '#2ecc71']
for body, color in zip(vp['bodies'], colors):
body.set_facecolor(color)
body.set_alpha(0.7)
ax.set_title('violinplot()')
ax.set_xticks([1, 2, 3])
ax.set_xticklabels(['Normal', 'Normal(wide)', 'Gamma'])
ax.grid(axis='y', alpha=0.3)
plt.show()
Matplotlib 参考文档
点我分享笔记