一、主流绘图库概览
1. 核心工具对比
库名称 | 特点 | 适用场景 |
---|---|---|
Matplotlib | 基础绘图库,高度可定制 | 科学绘图、论文图表 |
Seaborn | 基于Matplotlib,统计图表优化 | 数据分布、关系可视化 |
Plotly | 交互式可视化,支持网页输出 | 仪表盘、动态数据展示 |
Pandas | 内置简易绘图接口 | 快速数据探索 |
2. 环境准备
pip install matplotlib seaborn plotly pandas
二、Matplotlib基础与进阶
1. 基础绘图模板
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
matplotlib.rcParams['font.family'] = 'SimHei' # 使用黑体字体,根据实际情况修改
# 生成数据
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# 创建画布
plt.figure(figsize=(8, 4), dpi=100)
# 绘制曲线
plt.plot(x, y,
color='#FF6B6B', # 十六进制颜色
linestyle='--',
linewidth=2,
marker='o',
markersize=5,
label='sin(x)')
# 添加标注
plt.title("正弦函数曲线", fontsize=14, fontfamily='SimHei') # 解决中文显示
plt.xlabel("X轴", fontsize=12)
plt.ylabel("Y轴", fontsize=12)
plt.legend(loc='upper right') # 图例位置
# 网格与样式
plt.grid(True, linestyle=':', alpha=0.7)
plt.tight_layout() # 自动调整布局
# 显示/保存
plt.savefig('sine_curve.png', bbox_inches='tight') # 透明背景可加参数transparent=True
plt.show()
2. 多子图布局
fig, axes = plt.subplots(2, 2, figsize=(10, 8)) # 2行2列
# 第一个子图
axes[0,0].plot(x, np.sin(x), label='正弦')
axes[0,0].set_title('正弦曲线')
# 第二个子图
axes[0,1].scatter(x, np.cos(x), c='green', marker='^')
axes[0,1].set_title('余弦散点')
# 第三个子图(直方图)
axes[1,0].hist(np.random.randn(1000), bins=30,
edgecolor='black', alpha=0.7)
# 第四个子图(填充图)
axes[1,1].fill_between(x, np.sin(x), np.cos(x),
where=(np.sin(x) > np.cos(x)),
color='skyblue', alpha=0.4)
plt.tight_layout()
三、Seaborn高效统计绘图
1. 分布可视化
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
# 联合分布图
sns.jointplot(x='total_bill', y='tip', data=tips,
kind='hex', # 可选 'reg'、'kde'
marginal_kws={'color': '#4ECDC4'})
# 分类箱线图
plt.figure(figsize=(8,5))
sns.boxplot(x='day', y='total_bill', hue='sex',
data=tips, palette='Pastel1')
plt.title('每日消费分布')
2. 热力图与聚类
# 相关性热力图
corr = tips.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm',
linewidths=0.5, fmt='.2f')
# 聚类图
sns.clustermap(corr, cmap='viridis',
figsize=(6,6), method='ward')
import plotly.express as px
# 散点图矩阵
fig = px.scatter_matrix(iris,
dimensions=["sepal_length", "sepal_width",
"petal_length", "petal_width"],
color="species")
fig.show()
# 3D曲面图
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = px.surface(x=x, y=y, z=Z,
color_continuous_scale='Viridis')
fig.update_layout(title='3D曲面图')
fig.show()
四、Plotly交互式可视化
import plotly.graph_objects as go
import numpy as np
# 生成3D数据
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 = go.Figure(data=[
go.Surface(
z=Z,
colorscale='Viridis',
contours={ # 添加等高线
"z": {"show": True, "usecolormap": True}
}
)
])
# 添加控件按钮
fig.update_layout(
title='3D动态曲面图',
scene=dict(
xaxis_title='X轴',
yaxis_title='Y轴',
zaxis_title='Z值',
camera=dict( # 预设视角
eye=dict(x=1.5, y=1.5, z=0.1)
)
),
updatemenus=[ # 添加视角切换按钮
dict(
type="buttons",
buttons=[
dict(label="俯视",
method="relayout",
args=[{"scene.camera.eye": {"x": 0, "y": 0, "z": 2.5}}]),
dict(label="侧视",
method="relayout",
args=[{"scene.camera.eye": {"x": 2, "y": 2, "z": 0.1}}])
],
direction="left",
pad={"r": 10, "t": 10},
showactive=True,
x=0.1,
xanchor="left",
y=1.1,
yanchor="top"
)
]
)
fig.show()