matplotlib可视化大全|12种图表技巧+完整代码
一、基础2D图表
1. 折线图(Line Plot)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(10,6))
plt.plot(x, y, color='tab:blue', linestyle='--', linewidth=2,
label='正弦曲线', marker='o', markersize=5)
plt.title('正弦函数图像')
plt.xlabel('X轴(弧度)')
plt.ylabel('Y轴(值)')
plt.grid(True, alpha=0.3)
plt.legend(loc='upper right')
plt.axhline(y=0, color='k', linestyle=':', linewidth=1)
# 使用 annotate 添加带箭头的注释
plt.annotate('峰值点',
xy=(x[np.argmax(y)], np.sin(x[np.argmax(y)])),
xytext=(x[np.argmax(y)], 0.5),
arrowprops=dict(arrowstyle='->'),
bbox=dict(facecolor='white', alpha=0.7))
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
2. 散点图(Scatter Plot)
np.random.seed(42)
x = np.random.rand(50)
y = np.random.rand(50)
sizes = np.random.randint(20, 200, 50)
colors = np.random.rand(50)
plt.figure(figsize=(10,6))
scatter = plt.scatter(x, y, c=colors, s=sizes, alpha=0.7,
cmap='viridis', edgecolors='black')
plt.colorbar(scatter, label='颜色映射值')
plt.title('随机散点图')
plt.xlabel('X变量')
plt.ylabel('Y变量')
plt.annotate('数据密集区', xy=(0.5, 0.5), xytext=(0.7, 0.7),
arrowprops=dict(facecolor='red', shrink=0.05))
plt.show()
3. 柱状图(Bar Chart)
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 12, 67]
errors = [2, 3, 1, 4]
plt.figure(figsize=(10,6))
bars = plt.bar(categories, values, yerr=errors, capsize=5,
color=['#FF9999','#66B2FF','#99FF99','#FFD700'],
edgecolor='black', linewidth=1.5)
plt.title('分类数据对比')
plt.ylabel('数值')
plt.ylim(0, 80)
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height+1,
f'{height}', ha='center', va='bottom')
plt.axhline(y=np.mean(values), color='r', linestyle='--',
label=f'平均值{np.mean(values):.1f}')
plt.legend()
plt.show()
二、高级2D图表
4. 热力图(Heatmap)
data = np.random.rand(8, 8)
plt.figure(figsize=(10,8))
im = plt.imshow(data, cmap='hot', interpolation='nearest')
plt.colorbar(im, label='数值强度')
plt.title('热力图示例')
plt.xlabel('列索引')
plt.ylabel('行索引')
plt.xticks(np.arange(8))
plt.yticks(np.arange(8))
plt.grid(which='major', axis='both', linestyle='-', color='k', linewidth=0.5)
plt.show()
5. 等高线图(Contour Plot)
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
plt.figure(figsize=(10,8))
contour = plt.contour(X, Y, Z, levels=10, cmap='RdGy')
plt.clabel(contour, inline=True, fontsize=8)
plt.title('等高线图')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.grid(True, linestyle=':', alpha=0.5)
plt.show()
6. 蛛网图(Radar Chart)
labels=np.array(['沟通','技术','管理','创新','效率'])
stats=np.random.randint(50, 100, 5)
angles=np.linspace(0, 2*np.pi, len(labels), endpoint=False).tolist()
stats=np.concatenate((stats,[stats[0]]))
angles+=angles[:1]
fig, ax = plt.subplots(figsize=(8, 8),
subplot_kw=dict(polar=True))
ax.fill(angles, stats, color='red', alpha=0.25)
ax.plot(angles, stats, color='red', linewidth=2)
ax.set_thetagrids(np.degrees(angles[:-1]), labels)
ax.set_rlabel_position(30)
plt.title('能力雷达图')
plt.show()
三、3D可视化
7. 3D曲面图(Surface Plot)
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap='viridis',
linewidth=0, antialiased=True)
ax.set_xlabel('X轴')
ax.set_ylabel('Y轴')
ax.set_zlabel('Z轴')
ax.set_title('3D曲面图')
fig.colorbar(surf, shrink=0.5, aspect=5, label='函数值')
plt.show()
四、统计图表
8. 箱线图(Boxplot)
data = [np.random.normal(0, std, 100) for std in range(1,4)]
plt.figure(figsize=(10,6))
bp = plt.boxplot(data, notch=True, patch_artist=True)
colors = ['lightblue', 'lightgreen', 'salmon']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
plt.title('箱线图比较')
plt.xlabel('类别')
plt.ylabel('分布值')
plt.xticks([1,2,3], ['A','B','C'])
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()
五、动态可视化
9. 动态曲线(Animation)
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'b-', animated=True)
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True, interval=50)
plt.title('正弦波动态演示')
plt.show()
# 保存动画:ani.save('sine_wave.gif', writer='pillow')
六、其他特色图表
10. 极坐标图(Polar Plot)
theta = np.linspace(0, 2*np.pi, 100)
r = np.abs(np.sin(2*theta))
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, polar=True)
ax.plot(theta, r, 'r-', lw=2)
ax.fill(theta, r, 'skyblue', alpha=0.5)
ax.set_theta_zero_location('N')
ax.set_title('极坐标玫瑰图')
plt.show()
11. 小提琴图(Violin Plot)
data = [np.random.normal(0, 1, 100), np.random.normal(1, 0.8, 100)]
plt.figure(figsize=(10,6))
vp = plt.violinplot(data, showmeans=False, showmedians=True)
for pc in vp['bodies']:
pc.set_facecolor('#D43F3A')
pc.set_edgecolor('black')
pc.set_alpha(0.7)
plt.xticks([1,2], ['组A','组B'])
plt.ylabel('分布值')
plt.title('数据分布对比')
plt.show()
12. 饼图(Pie Chart)
labels = 'Python', 'Java', 'C++', 'JavaScript', 'Other'
sizes = [25, 20, 15, 30, 10]
explode = (0, 0.1, 0, 0.15, 0)
plt.figure(figsize=(10,7))
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90, textprops={'color':"w"})
plt.axis('equal')
plt.title('编程语言市场占有率')
plt.legend(title="语言", loc="best")
plt.show()
七、实用技巧总结
- 配色方案:使用
cmap
参数选择适合数据性质的色阶(如diverging/viridis/inferno) - 多子图布局:
plt.subplots(nrows, ncols)
创建多面板图形 - 交互式绘图:在Jupyter中使用
%matplotlib notebook
- 样式控制:通过
plt.style.use()
切换预设样式(如ggplot/seaborn) - 高精度保存:
plt.savefig('output.png', dpi=300, bbox_inches='tight')
完整代码已测试通过,建议收藏后逐个尝试!需要补充其他图表类型或具体应用场景的示例可以留言讨论~
研究学习不易,点赞易。
工作生活不易,收藏易,点收藏不迷茫 :)