一、Matplotlib 散点图
基本用法
import matplotlib.pyplot as plt
import numpy as np
# 生成示例数据
np.random.seed(42)
x = np.random.randn(100)
y = np.random.randn(100)
sizes = np.random.rand(100) * 100 # 点的大小
colors = np.random.rand(100) # 点的颜色
# 创建散点图
plt.figure(figsize=(10, 6))
scatter = plt.scatter(
x, y,
s=sizes, # 点的大小
c=colors, # 颜色
alpha=0.6, # 透明度
cmap='viridis', # 颜色映射
edgecolors='black', # 边缘颜色
linewidth=0.5
)
# 添加颜色条
plt.colorbar(scatter, label='Color Value')
# 添加标签和标题
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('Matplotlib 散点图示例')
plt.grid(True, alpha=0.3)
# 显示图形
plt.show()
分类散点图
import pandas as pd
# 创建分类数据
data = {
'x': np.random.randn(150),
'y': np.random.randn(150),
'category': np.random.choice(['A', 'B', 'C'], 150)
}
df = pd.DataFrame(data)
# 不同类别用不同颜色
plt.figure(figsize=(10, 6))
for category in df['category'].unique():
subset = df[df['category'] == category]
plt.scatter(
subset['x'], subset['y'],
label=category,
s=50,
alpha=0.7
)
plt.legend(title='类别')
plt.xlabel('特征X')
plt.ylabel('特征Y')
plt.title('分类散点图')
plt.grid(True, alpha=0.3)
plt.show()
二、Seaborn 散点图
基本用法
import seaborn as sns
import pandas as pd
# 使用内置数据集
tips = sns.load_dataset('tips')
# 创建散点图
plt.figure(figsize=(10, 6))
sns.scatterplot(
data=tips,
x='total_bill',
y='tip',
hue='day', # 按天着色
size='size', # 按大小分组
sizes=(50, 200), # 大小范围
alpha=0.7,
palette='Set2'
)
plt.title('Seaborn 散点图 - 小费数据')
plt.xlabel('总账单')
plt.ylabel('小费')
plt.legend(title='星期', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()
散点图矩阵(Pairplot)
# 散点图矩阵(适用于多变量分析)
iris = sns.load_dataset('iris')
sns.pairplot(
iris,
hue='species', # 按物种着色
palette='husl',
diag_kind='kde', # 对角线使用核密度估计
markers=['o', 's', 'D'], # 不同标记
plot_kws={'alpha': 0.7, 's': 50}
)
plt.suptitle('鸢尾花数据集 - 散点图矩阵', y=1.02)
plt.show()
带有回归线的散点图
plt.figure(figsize=(10, 6))
sns.regplot(
data=tips,
x='total_bill',
y='tip',
scatter_kws={'alpha': 0.6, 's': 50},
line_kws={'color': 'red', 'linewidth': 2},
ci=95 # 置信区间
)
plt.title('带有回归线的散点图')
plt.xlabel('总账单')
plt.ylabel('小费')
plt.show()
三、Pyecharts 散点图
基本用法
from pyecharts import options as opts
from pyecharts.charts import Scatter
import random
# 生成示例数据
x_data = [random.randint(0, 100) for _ in range(50)]
y_data = [random.randint(0, 100) for _ in range(50)]
# 创建散点图
scatter = (
Scatter()
.add_xaxis(x_data)
.add_yaxis(
"数据点",
y_data,
symbol_size=20,
label_opts=opts.LabelOpts(is_show=False)
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Pyecharts 散点图"),
xaxis_opts=opts.AxisOpts(
name="X轴",
type_="value",
splitline_opts=opts.SplitLineOpts(is_show=True)
),
yaxis_opts=opts.AxisOpts(
name="Y轴",
type_="value",
splitline_opts=opts.SplitLineOpts(is_show=True)
),
tooltip_opts=opts.TooltipOpts(
trigger="item",
formatter="{a}: ({c})"
),
visualmap_opts=opts.VisualMapOpts(
min_=min(y_data),
max_=max(y_data),
dimension=1,
orient="horizontal",
pos_left="center",
range_color=["#313695", "#4575b4", "#74add1", "#abd9e9",
"#e0f3f8", "#ffffbf", "#fee090", "#fdae61",
"#f46d43", "#d73027", "#a50026"]
)
)
)
scatter.render("pyecharts_scatter.html") # 保存为HTML文件
# scatter.render_notebook() # Jupyter中直接显示
多系列散点图
from pyecharts.charts import Scatter
import pandas as pd
import numpy as np
# 创建多系列数据
np.random.seed(42)
data = pd.DataFrame({
'x': np.random.randn(100),
'y': np.random.randn(100),
'category': np.random.choice(['Group A', 'Group B', 'Group C'], 100),
'value': np.random.rand(100) * 100
})
# 分组数据
groups = {}
for category in data['category'].unique():
group_data = data[data['category'] == category]
groups[category] = {
'x': group_data['x'].tolist(),
'y': group_data['y'].tolist(),
'value': group_data['value'].tolist()
}
# 创建多系列散点图
scatter = Scatter()
scatter.add_xaxis(data['x'].tolist())
# 添加不同系列
colors = ['#5470c6', '#91cc75', '#fac858']
symbols = ['circle', 'rect', 'triangle']
for (category, group_data), color, symbol in zip(groups.items(), colors, symbols):
scatter.add_yaxis(
series_name=category,
y_axis=group_data['y'],
symbol=symbol,
symbol_size=10,
color=color,
label_opts=opts.LabelOpts(is_show=False)
)
scatter.set_global_opts(
title_opts=opts.TitleOpts(title="多系列散点图"),
xaxis_opts=opts.AxisOpts(name="特征X"),
yaxis_opts=opts.AxisOpts(name="特征Y"),
tooltip_opts=opts.TooltipOpts(
trigger="item",
formatter="{b}: {c}"
),
legend_opts=opts.LegendOpts(pos_top="10%")
)
scatter.render("multi_scatter.html")
三维散点图
from pyecharts.charts import Scatter3D
from pyecharts import options as opts
import random
# 生成三维数据
data = [
[random.randint(0, 100) for _ in range(3)]
for _ in range(50)
]
scatter3d = (
Scatter3D()
.add(
"",
data,
grid3d_opts=opts.Grid3DOpts(width=100, height=100, depth=100),
label_opts=opts.LabelOpts(is_show=False)
)
.set_global_opts(
title_opts=opts.TitleOpts(title="三维散点图"),
visualmap_opts=opts.VisualMapOpts(
max_=100,
range_color=[
"#313695", "#4575b4", "#74add1", "#abd9e9", "#e0f3f8",
"#ffffbf", "#fee090", "#fdae61", "#f46d43", "#d73027", "#a50026"
]
)
)
)
scatter3d.render("scatter3d.html")
四、三种工具对比与选择建议
对比总结
| 特性 |
Matplotlib |
Seaborn |
Pyecharts |
|---|
| 易用性 |
较低 |
高 |
中 |
| 美观度 |
基础 |
高(默认好看) |
高(交互式) |
| 交互性 |
无 |
无 |
丰富 |
| 输出格式 |
静态图片 |
静态图片 |
HTML/Web |
| 学习曲线 |
较陡 |
平缓 |
中等 |
| 数据处理 |
需要预处理 |
内置数据处理 |
需要预处理 |
| 适合场景 |
科学论文、高度定制 |
数据探索、快速可视化 |
网页展示、交互报告 |
选择建议
Matplotlib:适合需要高度定制的科学图表、论文配图
Seaborn:适合数据探索分析、统计可视化、快速生成美观图表
Pyecharts:适合网页应用、交互式报告、动态数据展示
综合示例:同一数据用三种工具
# 生成测试数据
np.random.seed(42)
n = 100
x = np.random.randn(n)
y = x * 2 + np.random.randn(n) * 0.5
categories = np.random.choice(['A', 'B', 'C'], n)
sizes = np.abs(np.random.randn(n)) * 50
# 1. Matplotlib版本
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
# Matplotlib
axes[0].scatter(x, y, c=pd.Categorical(categories).codes, cmap='tab10', s=sizes, alpha=0.7)
axes[0].set_title('Matplotlib')
axes[0].grid(True, alpha=0.3)
# 2. Seaborn版本
df = pd.DataFrame({'x': x, 'y': y, 'category': categories, 'size': sizes})
sns.scatterplot(data=df, x='x', y='y', hue='category', size='size', ax=axes[1])
axes[1].set_title('Seaborn')
# 3. 为Pyecharts准备数据(单独绘制)
print("Pyecharts图表已生成HTML文件")
五、实用技巧
1. 大数据集优化
# Matplotlib大数据优化
plt.scatter(x, y, alpha=0.1, s=1) # 减小点大小和透明度
plt.hexbin(x, y, gridsize=30, cmap='Blues') # 使用六边形分箱
# Seaborn大数据优化
sns.kdeplot(x=x, y=y, fill=True, thresh=0, levels=100, cmap="rocket")
2. 添加趋势线
# Matplotlib添加趋势线
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x, p(x), "r--", alpha=0.8)
3. 颜色映射定制
# 自定义颜色映射
from matplotlib.colors import LinearSegmentedColormap
colors = ["#ff0000", "#ffff00", "#00ff00", "#0000ff"]
cmap = LinearSegmentedColormap.from_list("custom", colors, N=100)
4. 保存高质量图片
# 保存高清图片
plt.savefig('scatter.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
根据具体需求选择合适的工具,可以让数据可视化工作更加高效和美观。