Matplotlib 模块架构
matplotlib
├── pyplot (最常用) # 绘图接口
├── figure # 图形对象
├── axes # 坐标轴对象
├── artist # 图形元素
├── backend_bases # 后端基类
├── backends # 渲染后端
├── colors # 颜色系统
├── transforms # 坐标变换
├── patches # 形状
├── lines # 线条
├── text # 文本
├── ticker # 刻度
├── image # 图像处理
├── animation # 动画
├── widgets # 交互组件
└── style # 样式管理
plt.figure() - 创建图形
plt.figure(num=None, figsize=None, dpi=None,
facecolor=None, edgecolor=None, frameon=True,
clear=False, constrained_layout=False, layout=None)
参数说明:
num- 图形编号或名称(整数、字符串或Figure对象)
figsize- 图形大小(宽, 高),单位:英寸
dpi- 分辨率(每英寸点数),影响图形清晰度
facecolor- 图形背景颜色
edgecolor- 图形边框颜色
frameon- 是否显示图形边框
clear- 是否清除已存在的图形
constrained_layout- 是否使用自动约束布局
layout- 布局引擎('constrained', 'compressed', 'tight'等)
返回值类型:matplotlib.figure.Figure对象
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 创建带有详细设置的图形
fig = plt.figure(
num='my_figure_1', # 指定图形名称
figsize=(10, 6), # 设置图形大小为10x6英寸
dpi=100, # 设置分辨率为100DPI
facecolor='#F0F8FF', # 使用十六进制设置背景色(爱丽丝蓝)
edgecolor='#4682B4', # 设置边框颜色为钢蓝色
linewidth=2, # 边框宽度为2点
frameon=True, # 显示边框
constrained_layout=True # 启用自动布局
)
# 绘制简单数据
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# 绘制折线图
plt.plot(x, y,
color='#2E8B57', # 海绿色
linewidth=2, # 线宽2点
linestyle='-', # 实线
marker='o', # 圆形标记
markersize=4, # 标记大小4点
markerfacecolor='white', # 标记填充色
markeredgecolor='#2E8B57', # 标记边缘色
alpha=0.8, # 透明度0.8
label='正弦函数') # 图例标签
# 设置标题和标签
plt.title('图形创建示例 - plt.figure()函数演示',
fontsize=16,
fontweight='bold',
color='#2F4F4F', # 暗石板灰色
pad=20) # 标题与图形的间距
plt.xlabel('X轴 (弧度)',
fontsize=12,
fontweight='bold',
labelpad=10) # 标签与坐标轴的间距
plt.ylabel('Y轴 (函数值)',
fontsize=12,
fontweight='bold',
labelpad=10,
rotation=0) # 标签不旋转
# 显示图例
plt.legend(loc='upper right', # 图例位置在右上角
fontsize=10, # 图例字体大小
frameon=True, # 显示图例外框
fancybox=True, # 圆角边框
shadow=True, # 显示阴影
framealpha=0.9, # 边框透明度
borderpad=1) # 边框内边距
# 显示网格
plt.grid(True, # 启用网格
which='both', # 显示主次网格
axis='both', # 显示XY轴网格
color='gray', # 网格颜色
linestyle=':', # 点线样式
linewidth=0.5, # 网格线宽
alpha=0.3) # 网格透明度
# 设置坐标轴范围
plt.xlim(0, 2*np.pi) # X轴范围0到2π
plt.ylim(-1.2, 1.2) # Y轴范围-1.2到1.2
# 设置坐标轴刻度
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
['0', 'π/2', 'π', '3π/2', '2π'],
fontsize=10,
rotation=0)
plt.yticks([-1, -0.5, 0, 0.5, 1],
['-1.0', '-0.5', '0.0', '0.5', '1.0'],
fontsize=10)
# 添加参考线
plt.axhline(y=0, # 在y=0处画水平线
color='red', # 红色
linestyle='--', # 虚线
linewidth=1, # 线宽1点
alpha=0.5, # 透明度0.5
label='零线') # 图例标签
plt.axvline(x=np.pi, # 在x=π处画垂直线
color='green', # 绿色
linestyle=':', # 点线
linewidth=1, # 线宽1点
alpha=0.5, # 透明度0.5
label='x=π') # 图例标签
# 添加文本说明
plt.text(1, 0.8, # 文本位置(x=1, y=0.8)
'plt.figure()函数详解', # 文本内容
fontsize=12, # 字体大小
fontweight='bold', # 字体加粗
color='darkblue', # 文本颜色
ha='center', # 水平居中对齐
va='center', # 垂直居中对齐
bbox=dict( # 文本框设置
boxstyle='round', # 圆角文本框
facecolor='lightyellow', # 背景色
edgecolor='orange', # 边框色
linewidth=2, # 边框线宽
alpha=0.8 # 透明度
))
# 显示图形
plt.show()
# 打印图形信息
print("图形信息:")
print(f" 图形编号: {fig.number}")
print(f" 图形大小: {fig.get_size_inches()} 英寸")
print(f" 图形DPI: {fig.dpi}")
print(f" 背景颜色: {fig.get_facecolor()}")
print(f" 边框颜色: {fig.get_edgecolor()}")
print(f" 边框宽度: {fig.get_linewidth()}")
图形信息:
图形编号: 1
图形大小: [10. 6.] 英寸
图形DPI: 125.0
背景颜色: (0.9411764705882353, 0.9725490196078431, 1.0, 1.0)
边框颜色: (0.27450980392156865, 0.5098039215686274, 0.7058823529411765, 1.0)
边框宽度: 2.0

plt.subplot() - 创建子图
plt.subplot(nrows, ncols, index, **kwargs)
参数说明:
nrows- 子图网格的行数
ncols- 子图网格的列数
index- 子图位置索引(从1开始)
**kwargs- 传递给add_subplot的其他参数
返回值类型:matplotlib.axes.Axes对象
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 创建2x2的子图布局
plt.figure(figsize=(12, 8), facecolor='#F5F5F5')
# 子图1:折线图
plt.subplot(2, 2, 1) # 2行2列,第1个位置
x1 = np.linspace(0, 10, 100)
y1 = np.sin(x1)
plt.plot(x1, y1, 'b-', linewidth=2, alpha=0.8)
plt.fill_between(x1, y1, 0, alpha=0.2, color='blue')
plt.title('子图1: 正弦函数', fontsize=12, fontweight='bold')
plt.xlabel('X轴', fontsize=10)
plt.ylabel('Y轴', fontsize=10)
plt.grid(True, alpha=0.3)
plt.axhline(y=0, color='red', linestyle='--', linewidth=1, alpha=0.5)
# 子图2:散点图
plt.subplot(2, 2, 2) # 2行2列,第2个位置
np.random.seed(42)
x2 = np.random.randn(50)
y2 = np.random.randn(50)
colors2 = np.random.rand(50)
sizes2 = 20 + 100 * np.random.rand(50)
plt.scatter(x2, y2, s=sizes2, c=colors2,
marker='o', alpha=0.6, edgecolors='w', linewidths=0.5)
plt.title('子图2: 随机散点图', fontsize=12, fontweight='bold')
plt.xlabel('X值', fontsize=10)
plt.ylabel('Y值', fontsize=10)
plt.grid(True, alpha=0.3)
# 子图3:柱状图
plt.subplot(2, 2, 3) # 2行2列,第3个位置
categories = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
values = [25, 40, 30, 35, 20]
colors3 = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
bars = plt.bar(categories, values,
color=colors3, edgecolor='black', linewidth=1, alpha=0.8)
plt.title('子图3: 水果销售额', fontsize=12, fontweight='bold')
plt.xlabel('水果种类', fontsize=10)
plt.ylabel('销售额(万元)', fontsize=10)
plt.grid(True, alpha=0.3, axis='y')
# 添加数值标签
for bar, value in zip(bars, values):
plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
str(value), ha='center', va='bottom', fontsize=9, fontweight='bold')
# 子图4:饼图
plt.subplot(2, 2, 4) # 2行2列,第4个位置
sizes = [30, 25, 20, 15, 10]
labels = ['A', 'B', 'C', 'D', 'E']
explode = (0.1, 0, 0, 0, 0) # 突出第一块
plt.pie(sizes, explode=explode, labels=labels,
autopct='%1.1f%%', startangle=90,
colors=colors3, shadow=True)
plt.title('子图4: 比例分布饼图', fontsize=12, fontweight='bold')
# 添加总标题
plt.suptitle('plt.subplot()函数示例 - 2×2子图布局',
fontsize=16, fontweight='bold', y=0.98)
# 调整布局防止重叠
plt.tight_layout(rect=[0, 0, 1, 0.96]) # 调整子图位置
plt.show()

plt.subplots() - 创建多个子图
plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False,
squeeze=True, subplot_kw=None, gridspec_kw=None,
**fig_kw)
参数中文说明:
nrows- 行数(默认1)
ncols- 列数(默认1)
sharex- 是否共享X轴(False/'none'/'all'/'row'/'col')
sharey- 是否共享Y轴(False/'none'/'all'/'row'/'col')
squeeze- 是否压缩维度
subplot_kw- 传递给add_subplot的关键字参数字典
gridspec_kw- 传递给GridSpec的关键字参数字典
**fig_kw- 传递给figure的关键字参数
返回值类型:(matplotlib.figure.Figure, numpy.ndarray)元组
Figure对象
Axes对象数组(形状为(nrows, ncols)
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
fig, axes = plt.subplots(
nrows=3, # 3行
ncols=3, # 3列
figsize=(16, 14), # 图形大小
sharex=False, # 共享X轴
sharey=False, # 共享Y轴
constrained_layout=False, # 自动布局
facecolor='#F8F9FA' # 背景色
)
# 调整子图间距
plt.subplots_adjust(
left=0.05, # 左侧边距
right=0.95, # 右侧边距
bottom=0.07, # 底部边距
top=0.92, # 顶部边距
wspace=0.3, # 水平间距
hspace=0.35 # 垂直间距
)
# 生成示例数据
np.random.seed(42)
x = np.linspace(0, 10, 100)
# 遍历所有子图并绘制
for i in range(3):
for j in range(3):
ax = axes[i, j] # 获取当前子图
# 根据不同位置绘制不同类型图表
if i == 0 and j == 0:
# 左上角:正弦函数
y = np.sin(x)
ax.plot(x, y, 'b-', linewidth=2, label='sin(x)')
ax.set_title('正弦函数', fontsize=12, fontweight='bold')
ax.legend(loc='upper right', fontsize=9)
elif i == 0 and j == 1:
# 余弦函数
y = np.cos(x)
ax.plot(x, y, 'r-', linewidth=2, label='cos(x)')
ax.set_title('余弦函数', fontsize=12, fontweight='bold')
ax.legend(loc='upper right', fontsize=9)
elif i == 0 and j == 2:
# 正切函数
y = np.tan(x)
ax.plot(x, y, 'g-', linewidth=2, label='tan(x)')
ax.set_title('正切函数', fontsize=12, fontweight='bold')
ax.set_ylim(-5, 5) # 限制Y轴范围
ax.legend(loc='upper right', fontsize=9)
elif i == 1 and j == 0:
# 随机散点图
x_scatter = np.random.randn(50)
y_scatter = np.random.randn(50)
colors = np.random.rand(50)
sizes = 20 + 100 * np.random.rand(50)
scatter = ax.scatter(x_scatter, y_scatter,
s=sizes, c=colors,
alpha=0.6, edgecolors='w', linewidths=0.5)
ax.set_title('随机散点图', fontsize=12, fontweight='bold')
elif i == 1 and j == 1:
# 柱状图
categories = ['A', 'B', 'C', 'D', 'E']
values = [3, 7, 5, 9, 6]
bars = ax.bar(categories, values,
color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'],
edgecolor='black', linewidth=1, alpha=0.8)
ax.set_title('柱状图', fontsize=12, fontweight='bold')
# 添加数值标签
for bar, value in zip(bars, values):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.2,
str(value), ha='center', va='bottom', fontsize=9, fontweight='bold')
elif i == 1 and j == 2:
# 直方图
data = np.random.randn(1000)
ax.hist(data, bins=30,
color='lightblue', edgecolor='black',
linewidth=1, alpha=0.7, density=True)
ax.set_title('正态分布直方图', fontsize=12, fontweight='bold')
elif i == 2 and j == 0:
# 饼图
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
ax.pie(sizes, labels=labels,
autopct='%1.1f%%', startangle=90,
colors=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4'])
ax.set_title('饼图', fontsize=12, fontweight='bold')
elif i == 2 and j == 1:
# 箱线图
data = [np.random.normal(0, 1, 100),
np.random.normal(2, 1.5, 100),
np.random.normal(4, 0.8, 100)]
box = ax.boxplot(data, patch_artist=True)
# 设置颜色
colors_box = ['lightblue', 'lightgreen', 'lightcoral']
for patch, color in zip(box['boxes'], colors_box):
patch.set_facecolor(color)
ax.set_title('箱线图', fontsize=12, fontweight='bold')
ax.set_xticklabels(['组1', '组2', '组3'])
else: # i == 2 and j == 2
# 面积图
x_area = np.linspace(0, 10, 100)
y1_area = np.sin(x_area)
y2_area = np.cos(x_area)
ax.plot(x_area, y1_area, 'b-', linewidth=2, label='sin(x)')
ax.plot(x_area, y2_area, 'r-', linewidth=2, label='cos(x)')
ax.fill_between(x_area, y1_area, y2_area,
where=(y1_area > y2_area),
color='blue', alpha=0.3, label='sin>cos')
ax.fill_between(x_area, y1_area, y2_area,
where=(y1_area <= y2_area),
color='red', alpha=0.3, label='cos≥sin')
ax.set_title('面积图', fontsize=12, fontweight='bold')
ax.legend(loc='upper right', fontsize=9)
# 为所有子图添加网格
ax.grid(True, alpha=0.3)
# 为底部行的子图添加X轴标签
if i == 2:
ax.set_xlabel('X轴', fontsize=10)
# 为左侧列的子图添加Y轴标签
if j == 0:
ax.set_ylabel('Y轴', fontsize=10)
# 添加总标题
fig.suptitle('plt.subplots()函数示例 - 3×3子图网格',
fontsize=18, fontweight='bold', y=0.98)
plt.show()
# 打印子图信息
print("子图网格信息:")
print(f" 行数: {len(axes)}")
print(f" 列数: {len(axes[0])}")
print(f" 总子图数: {axes.size}")
子图网格信息:
行数: 3
列数: 3
总子图数: 9

plt.plot() - 折线图
plt.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
参数中文说明:
*args- 数据参数,可以是y或x,y
scalex, scaley- 是否自动缩放坐标轴
data- 包含标签数据的对象
color/c- 线条颜色
linestyle/ls- 线型('-', '--', '-.', ':')
linewidth/lw- 线宽
marker- 标记形状
markersize/ms- 标记大小
markeredgecolor/mec- 标记边缘颜色
markerfacecolor/mfc- 标记填充颜色
alpha- 透明度
label- 图例标签
zorder- 绘图顺序
返回值类型:包含线条对象的列表(list[matplotlib.lines.Line2D])
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 创建图形
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6),
facecolor='#F8F9FA')
# 生成数据
x = np.linspace(0, 4*np.pi, 100)
y_sin = np.sin(x)
y_cos = np.cos(x)
y_tan = np.tan(x) / 10 # 缩放正切函数
# 子图1:基本折线图
ax1.plot(x, y_sin,
color='blue', # 线条颜色
linestyle='-', # 实线
linewidth=2.5, # 线宽2.5点
marker='o', # 圆形标记
markersize=6, # 标记大小6点
markerfacecolor='white', # 标记填充白色
markeredgecolor='blue', # 标记边缘蓝色
markeredgewidth=1, # 标记边缘线宽
alpha=0.8, # 透明度0.8
label='sin(x)', # 图例标签
zorder=3) # 绘图顺序
ax1.plot(x, y_cos,
color='red', # 红色
linestyle='--', # 虚线
linewidth=2.5, # 线宽2.5点
marker='s', # 方形标记
markersize=5, # 标记大小5点
markerfacecolor='white', # 标记填充白色
markeredgecolor='red', # 标记边缘红色
markeredgewidth=1, # 标记边缘线宽
alpha=0.8, # 透明度0.8
label='cos(x)', # 图例标签
zorder=2) # 绘图顺序
# 设置子图1属性
ax1.set_title('基本折线图 - plt.plot()', fontsize=14, fontweight='bold')
ax1.set_xlabel('角度 (弧度)', fontsize=12)
ax1.set_ylabel('函数值', fontsize=12)
ax1.legend(loc='upper right', fontsize=10, framealpha=0.9)
ax1.grid(True, alpha=0.3, linestyle=':', linewidth=0.8)
ax1.set_xlim(0, 4*np.pi)
ax1.set_ylim(-1.2, 1.2)
# 设置X轴刻度
ax1.set_xticks([0, np.pi, 2*np.pi, 3*np.pi, 4*np.pi])
ax1.set_xticklabels(['0', 'π', '2π', '3π', '4π'], fontsize=10)
# 添加参考线
ax1.axhline(y=0, color='gray', linestyle='-', linewidth=1, alpha=0.5, zorder=1)
ax1.axvline(x=np.pi, color='green', linestyle=':', linewidth=1, alpha=0.5, zorder=1)
# 子图2:高级折线图(多条线,不同样式)
# 定义不同的线型和标记
line_styles = ['-', '--', '-.', ':']
markers = ['o', 's', '^', 'v', '<', '>', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_']
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
# 绘制多条不同样式的线
for i in range(8):
y = np.sin(x + i*0.5) * 0.8 # 相位偏移的正弦波
ax2.plot(x, y,
color=colors[i % len(colors)], # 循环使用颜色
linestyle=line_styles[i % len(line_styles)], # 循环使用线型
linewidth=1.5 + i*0.2, # 逐渐增加线宽
marker=markers[i % len(markers)], # 循环使用标记
markersize=4 + i*0.5, # 逐渐增加标记大小
markerfacecolor='white', # 标记填充白色
markeredgewidth=1, # 标记边缘线宽
alpha=0.7 - i*0.05, # 逐渐降低透明度
label=f'波 {i+1} (相位={i*0.5:.1f})', # 动态标签
zorder=10-i) # 绘图顺序递减
# 设置子图2属性
ax2.set_title('多线折线图 - 不同样式演示', fontsize=14, fontweight='bold', pad=10)
ax2.set_xlabel('X轴', fontsize=12)
ax2.set_ylabel('Y轴', fontsize=12)
ax2.legend(loc='upper right', fontsize=8, ncol=2, framealpha=0.9)
ax2.grid(True, alpha=0.3, linestyle='--', linewidth=0.5)
ax2.set_xlim(0, 4*np.pi)
ax2.set_ylim(-1.2, 1.2)
# 设置X轴刻度
ax2.set_xticks([0, np.pi, 2*np.pi, 3*np.pi, 4*np.pi])
ax2.set_xticklabels(['0', 'π', '2π', '3π', '4π'], fontsize=10)
# 设置Y轴刻度,增加刻度点以缩小间距
ax2.set_yticks(np.arange(-1.2, 1.3, 0.2))
ax2.set_yticklabels([-1.2, -1.0, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2], fontsize=9)
# 添加填充区域
ax2.fill_between(x, 0.5, 1.0, alpha=0.2, color='green', label='高值区域')
ax2.fill_between(x, -1.0, -0.5, alpha=0.2, color='red', label='低值区域')
# 添加文本说明,调整位置避免与标题重叠
ax2.text(0.4, 0.95,
'plt.plot()参数演示\n颜色、线型、标记、线宽、透明度',
transform=ax2.transAxes,
fontsize=10,
fontweight='bold',
color='darkblue',
ha='right',
va='top',
bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.8))
# 调整布局,为总标题留出更多空间
plt.subplots_adjust(top=0.85)
# 添加总标题
plt.suptitle('plt.plot() 折线图函数详解',
fontsize=16, fontweight='bold', y=0.98)
plt.show()
# 打印常用参数总结
print("plt.plot() 常用参数总结:")
print("="*50)
print("颜色参数:")
print(" color/c: 线条颜色 (如 'red', '#FF0000', (1,0,0))")
print(" markerfacecolor/mfc: 标记填充色")
print(" markeredgecolor/mec: 标记边缘色")
print()
print("线型参数:")
print(" linestyle/ls: 线型 ('-', '--', '-.', ':', 'None')")
print(" linewidth/lw: 线宽 (如 2, 2.5)")
print()
print("标记参数:")
print(" marker: 标记形状 (如 'o', 's', '^', 'v', '*', '+', 'x')")
print(" markersize/ms: 标记大小")
print(" markeredgewidth/mew: 标记边缘线宽")
print()
print("其他参数:")
print(" alpha: 透明度 (0-1)")
print(" label: 图例标签")
print(" zorder: 绘图顺序 (数值越大越靠前)")
print(" scalex/scaley: 是否自动缩放坐标轴")
plt.plot() 常用参数总结:
==================================================
颜色参数:
color/c: 线条颜色 (如 'red', '#FF0000', (1,0,0))
markerfacecolor/mfc: 标记填充色
markeredgecolor/mec: 标记边缘色
线型参数:
linestyle/ls: 线型 ('-', '--', '-.', ':', 'None')
linewidth/lw: 线宽 (如 2, 2.5)
标记参数:
marker: 标记形状 (如 'o', 's', '^', 'v', '*', '+', 'x')
markersize/ms: 标记大小
markeredgewidth/mew: 标记边缘线宽
其他参数:
alpha: 透明度 (0-1)
label: 图例标签
zorder: 绘图顺序 (数值越大越靠前)
scalex/scaley: 是否自动缩放坐标轴

plt.scatter() - 散点图
plt.scatter(x, y, s=None, c=None, marker=None, cmap=None,
norm=None, vmin=None, vmax=None, alpha=None,
linewidths=None, edgecolors=None, plotnonfinite=False,
data=None, **kwargs)
参数中文说明:
x, y- 数据点的x,y坐标
s- 点的大小(标量或数组,默认20)
c- 点的颜色(颜色、颜色数组或颜色映射)
marker- 标记形状
cmap- 颜色映射(当c是数值数组时使用)
norm- 颜色归一化
vmin, vmax- 颜色映射范围
alpha- 透明度
linewidths- 边缘线宽
edgecolors- 边缘颜色
plotnonfinite- 是否绘制非有限值
**kwargs- 其他参数
返回值类型:matplotlib.collections.PathCollection对象
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 创建图形
fig, axes = plt.subplots(2, 2, figsize=(16, 8),
facecolor='#F8F9FA')
# 生成示例数据
np.random.seed(42)
n = 100
x = np.random.randn(n) * 2
y = np.random.randn(n) * 2
# 子图1:基本散点图
ax1 = axes[0, 0]
# 创建不同类别的数据
category = np.random.choice(['A', 'B', 'C'], n)
colors_map = {'A': 'red', 'B': 'green', 'C': 'blue'}
sizes_map = {'A': 50, 'B': 100, 'C': 150}
# 按类别绘制散点
scatter_objects = [] # 保存散点对象
for cat in ['A', 'B', 'C']:
mask = category == cat
scatter = ax1.scatter(x[mask], y[mask], # 返回值:PathCollection对象
s=sizes_map[cat], # 点的大小
c=colors_map[cat], # 点的颜色
marker='o', # 圆形标记
alpha=0.7, # 透明度
edgecolors='white', # 边缘白色
linewidths=1, # 边缘线宽1点
label=f'类别 {cat}') # 图例标签
scatter_objects.append(scatter)
ax1.set_title('1. 基本散点图 (按类别)', fontsize=12, fontweight='bold')
ax1.set_xlabel('X值', fontsize=10)
ax1.set_ylabel('Y值', fontsize=10)
ax1.legend(loc='upper right', fontsize=9)
ax1.grid(True, alpha=0.3, linestyle=':', linewidth=0.8)
ax1.set_xlim(-5, 5)
ax1.set_ylim(-5, 5)
# 子图2:气泡图(大小表示第三维)
ax2 = axes[0, 1]
# 生成第三维数据
z = np.random.rand(n) * 10 # 第三维数据,用于控制大小
category2 = np.random.rand(n) # 用于控制颜色的连续值
# 绘制气泡图
scatter2 = ax2.scatter(x, y, # 返回值:PathCollection对象
s=z*20, # 大小与z值成正比
c=category2, # 颜色为连续值
cmap='viridis', # 使用viridis颜色映射
marker='o', # 圆形标记
alpha=0.6, # 透明度
edgecolors='white', # 边缘白色
linewidths=0.5, # 边缘线宽
vmin=0, vmax=1) # 颜色映射范围
# 添加颜色条
cbar2 = plt.colorbar(scatter2, ax=ax2, label='颜色值')
ax2.set_title('2. 气泡图 (大小=第三维, 颜色=第四维)', fontsize=12, fontweight='bold')
ax2.set_xlabel('X值', fontsize=10)
ax2.set_ylabel('Y值', fontsize=10)
ax2.grid(True, alpha=0.3, linestyle=':', linewidth=0.8)
ax2.set_xlim(-5, 5)
ax2.set_ylim(-5, 5)
# 子图3:带回归线的散点图
ax3 = axes[1, 0]
# 创建有相关性的数据
np.random.seed(42)
n3 = 50
x3 = np.random.randn(n3) * 2
y3 = 1.5 * x3 + np.random.randn(n3) * 1.0 # 线性关系加噪声
colors3 = np.abs(x3) # 颜色基于x的绝对值
sizes3 = 30 + 100 * np.random.rand(n3) # 随机大小
# 绘制散点
scatter3 = ax3.scatter(x3, y3, # 返回值:PathCollection对象
s=sizes3, # 随机大小
c=colors3, # 颜色基于x值
cmap='coolwarm', # 冷暖色映射
marker='s', # 方形标记
alpha=0.7, # 透明度
edgecolors='black', # 黑色边缘
linewidths=0.8, # 边缘线宽
label='数据点')
# 计算并绘制回归线
coeff = np.polyfit(x3, y3, 1) # 一次多项式拟合
poly = np.poly1d(coeff)
x_fit = np.linspace(min(x3), max(x3), 100)
y_fit = poly(x_fit)
ax3.plot(x_fit, y_fit, 'r-', linewidth=2,
label=f'回归线: y={coeff[0]:.2f}x+{coeff[1]:.2f}')
# 添加颜色条
cbar3 = plt.colorbar(scatter3, ax=ax3, label='|X|值')
ax3.set_title('3. 带回归线的散点图', fontsize=12, fontweight='bold')
ax3.set_xlabel('X值', fontsize=10)
ax3.set_ylabel('Y值', fontsize=10)
ax3.legend(loc='upper left', fontsize=9)
ax3.grid(True, alpha=0.3, linestyle=':', linewidth=0.8)
# 子图4:高级散点图(多种标记和样式)
ax4 = axes[1, 1]
# 生成4组不同类别的数据
n4 = 25
markers4 = ['o', 's', '^', 'v', 'D', 'p', '*', 'h']
colors4 = plt.cm.Set3(np.linspace(0, 1, 8))
scatter_list = [] # 保存所有散点对象
for i in range(8):
# 生成每组数据
x4 = np.random.randn(n4) + i*1.5
y4 = np.random.randn(n4) + i*1.5
sizes4 = 20 + 80 * np.random.rand(n4)
# 绘制每组数据
scatter = ax4.scatter(x4, y4, # 返回值:PathCollection对象
s=sizes4, # 随机大小
c=[colors4[i]], # 固定颜色
marker=markers4[i], # 不同标记
alpha=0.7, # 透明度
edgecolors='black', # 黑色边缘
linewidths=1, # 边缘线宽
label=f'组 {i+1} ({markers4[i]})') # 图例包含标记类型
scatter_list.append(scatter)
ax4.set_title('4. 多种标记样式散点图', fontsize=12, fontweight='bold')
ax4.set_xlabel('X值', fontsize=10)
ax4.set_ylabel('Y值', fontsize=10)
ax4.legend(loc='upper left', fontsize=8, ncol=2)
ax4.grid(True, alpha=0.3, linestyle=':', linewidth=0.8)
# 调整布局,为总标题留出足够空间
plt.subplots_adjust(
top=0.85, # 为总标题留出空间
bottom=0.08, # 底部边距
left=0.05, # 左侧边距
right=0.95, # 右侧边距
wspace=0.3, # 水平间距
hspace=0.4 # 垂直间距
)
# 添加总标题
fig.suptitle('plt.scatter() 散点图函数详解',
fontsize=16, fontweight='bold', y=0.98)
# 保存图表到文件,避免显示阻塞
plt.savefig('scatter_demo.png', dpi=100, bbox_inches='tight')
print("图表已保存为: scatter_demo.png")
# 关闭图表
plt.close()
# 打印返回值信息
print("plt.scatter() 返回值信息:")
print("="*60)
print(f"返回值类型: {type(scatter2)}")
print(f"子图1散点对象数量: {len(scatter_objects)}")
print(f"子图4散点对象数量: {len(scatter_list)}")
print("\nPathCollection对象主要属性:")
print(" - sizes: 点的大小数组")
print(" - colors: 点的颜色数组")
print(" - edgecolors: 边缘颜色数组")
print(" - linewidths: 边缘线宽数组")
print(" - get_offsets(): 获取点的坐标")
print(" - get_sizes(): 获取点的大小")
print(" - get_facecolors(): 获取填充颜色")
图表已保存为: scatter_demo.png
plt.scatter() 返回值信息:
============================================================
返回值类型: <class 'matplotlib.collections.PathCollection'>
子图1散点对象数量: 3
子图4散点对象数量: 8
PathCollection对象主要属性:
- sizes: 点的大小数组
- colors: 点的颜色数组
- edgecolors: 边缘颜色数组
- linewidths: 边缘线宽数组
- get_offsets(): 获取点的坐标
- get_sizes(): 获取点的大小
- get_facecolors(): 获取填充颜色

plt.bar() - 柱状图
plt.bar(x, height, width=0.8, bottom=None, align='center',
data=None, **kwargs)
参数中文说明:
x- 柱子的x坐标
height- 柱子高度
width- 柱子宽度(默认0.8)
bottom- 柱子底部y坐标(用于堆叠柱状图)
align- 对齐方式('center'或'edge')
color- 柱子颜色
edgecolor- 边缘颜色
linewidth- 边缘线宽
tick_label- 刻度标签
xerr, yerr- 误差线
ecolor- 误差线颜色
capsize- 误差线帽子大小
error_kw- 误差线参数字典
hatch- 填充图案
alpha- 透明度
label- 图例标签
返回值类型:包含矩形对象的列表(list[matplotlib.patches.Rectangle])
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 创建图形
fig, axes = plt.subplots(2, 2, figsize=(16, 9),
facecolor='#F8F9FA')
# 数据准备
months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales_2023 = [120, 150, 180, 220, 190, 210]
sales_2024 = [140, 170, 200, 240, 220, 250]
sales_2025 = [160, 190, 220, 260, 240, 270]
errors = [10, 15, 12, 18, 14, 16] # 误差值
# 子图1:基本柱状图
ax1 = axes[0, 0]
x1 = np.arange(len(months))
width1 = 0.6
# 绘制柱状图
bars1 = ax1.bar(x1, sales_2023, # 返回值:矩形对象列表
width=width1, # 柱子宽度
color='lightblue', # 柱子颜色
edgecolor='darkblue', # 边缘颜色
linewidth=2, # 边缘线宽
alpha=0.8, # 透明度
hatch='/', # 填充图案:斜线
label='2023年', # 图例标签
tick_label=months, # 刻度标签
yerr=errors, # Y方向误差
ecolor='red', # 误差线颜色
capsize=5, # 误差线帽子大小
error_kw={ # 误差线参数
'elinewidth': 2,
'capthick': 2
})
# 添加数值标签
for bar, value, error in zip(bars1, sales_2023, errors):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2, height + error + 5,
f'{value}', ha='center', va='bottom',
fontsize=9, fontweight='bold')
ax1.set_title('1. 基本柱状图 (带误差棒)', fontsize=12, fontweight='bold')
ax1.set_xlabel('月份', fontsize=10)
ax1.set_ylabel('销售额 (万元)', fontsize=10)
ax1.legend(loc='upper left', fontsize=9)
ax1.grid(True, alpha=0.3, axis='y')
ax1.set_ylim(0, 300)
# 子图2:分组柱状图
ax2 = axes[0, 1]
x2 = np.arange(len(months))
width2 = 0.25
# 绘制三组柱状图
bars2_2023 = ax2.bar(x2 - width2, sales_2023, width2, # 返回值:矩形对象列表
color='lightblue',
edgecolor='darkblue',
linewidth=1,
alpha=0.8,
label='2023年')
bars2_2024 = ax2.bar(x2, sales_2024, width2, # 返回值:矩形对象列表
color='lightgreen',
edgecolor='darkgreen',
linewidth=1,
alpha=0.8,
label='2024年')
bars2_2025 = ax2.bar(x2 + width2, sales_2025, width2, # 返回值:矩形对象列表
color='lightcoral',
edgecolor='darkred',
linewidth=1,
alpha=0.8,
label='2025年')
# 添加数值标签
def add_labels(bars):
for bar in bars:
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2, height + 2,
f'{height}', ha='center', va='bottom',
fontsize=8, fontweight='bold')
add_labels(bars2_2023)
add_labels(bars2_2024)
add_labels(bars2_2025)
ax2.set_title('2. 分组柱状图', fontsize=12, fontweight='bold')
ax2.set_xlabel('月份', fontsize=10)
ax2.set_ylabel('销售额 (万元)', fontsize=10)
ax2.set_xticks(x2)
ax2.set_xticklabels(months)
ax2.legend(loc='upper left', fontsize=9)
ax2.grid(True, alpha=0.3, axis='y')
ax2.set_ylim(0, 300)
# 子图3:堆叠柱状图
ax3 = axes[1, 0]
# 模拟各部门销售额
dept_a = [30, 40, 50, 60, 55, 45]
dept_b = [50, 55, 60, 70, 65, 75]
dept_c = [40, 55, 70, 90, 70, 90]
# 绘制堆叠柱状图
bars3_a = ax3.bar(months, dept_a, # 返回值:矩形对象列表
color='lightblue',
edgecolor='darkblue',
linewidth=1,
alpha=0.8,
label='部门A')
bars3_b = ax3.bar(months, dept_b, bottom=dept_a, # 返回值:矩形对象列表
color='lightgreen',
edgecolor='darkgreen',
linewidth=1,
alpha=0.8,
label='部门B')
bars3_c = ax3.bar(months, dept_c, # 返回值:矩形对象列表
bottom=[a+b for a,b in zip(dept_a, dept_b)],
color='lightcoral',
edgecolor='darkred',
linewidth=1,
alpha=0.8,
label='部门C')
# 计算总销售额并添加标签
total_sales = [a+b+c for a,b,c in zip(dept_a, dept_b, dept_c)]
for i, (month, total) in enumerate(zip(months, total_sales)):
ax3.text(i, total + 5, f'{total}',
ha='center', va='bottom',
fontsize=9, fontweight='bold')
ax3.set_title('3. 堆叠柱状图', fontsize=12, fontweight='bold')
ax3.set_xlabel('月份', fontsize=10)
ax3.set_ylabel('销售额 (万元)', fontsize=10)
ax3.legend(loc='upper left', fontsize=9)
ax3.grid(True, alpha=0.3, axis='y')
ax3.set_ylim(0, 250)
# 子图4:水平柱状图
ax4 = axes[1, 1]
# 按销售额排序
sorted_indices = np.argsort(sales_2024)[::-1] # 降序排列
sorted_months = [months[i] for i in sorted_indices]
sorted_sales = [sales_2024[i] for i in sorted_indices]
# 使用渐变色
colors4 = plt.cm.Blues(np.linspace(0.3, 0.9, len(months)))
# 绘制水平柱状图
bars4 = ax4.barh(sorted_months, sorted_sales, # 返回值:矩形对象列表
color=colors4, # 渐变色
edgecolor='black', # 黑色边缘
linewidth=1, # 边缘线宽
height=0.6, # 柱子高度(水平图的宽度)
alpha=0.8, # 透明度
hatch='\\') # 填充图案
# 添加数值标签
for bar, value in zip(bars4, sorted_sales):
width = bar.get_width()
ax4.text(width + 2, bar.get_y() + bar.get_height()/2,
f'{value}', va='center',
fontsize=9, fontweight='bold')
ax4.set_title('4. 水平柱状图 (排序后)', fontsize=12, fontweight='bold')
ax4.set_xlabel('销售额 (万元)', fontsize=10)
ax4.set_ylabel('月份', fontsize=10)
ax4.grid(True, alpha=0.3, axis='x')
ax4.set_xlim(0, 300)
# 调整布局,为总标题留出足够空间
plt.subplots_adjust(
top=0.85, # 为总标题留出空间
bottom=0.08, # 底部边距
left=0.05, # 左侧边距
right=0.95, # 右侧边距
wspace=0.3, # 水平间距
hspace=0.4 # 垂直间距
)
# 添加总标题
fig.suptitle('plt.bar() 柱状图函数详解',
fontsize=16, fontweight='bold', y=0.95)
# 保存图表到文件,避免显示阻塞
plt.savefig('bar_demo.png', dpi=100, bbox_inches='tight')
print("图表已保存为: bar_demo.png")
# 关闭图表
plt.close()
# 打印返回值信息
print("plt.bar() 返回值信息:")
print("="*60)
print(f"返回值类型: {type(bars1)}")
print(f"子图1矩形对象数量: {len(bars1)}")
print(f"子图2矩形对象总数: {len(bars2_2023) + len(bars2_2024) + len(bars2_2025)}")
print("\nRectangle对象主要属性:")
print(" - get_height(): 获取柱子高度")
print(" - get_width(): 获取柱子宽度")
print(" - get_x(): 获取柱子x坐标")
print(" - get_y(): 获取柱子y坐标")
print(" - get_facecolor(): 获取填充颜色")
print(" - get_edgecolor(): 获取边缘颜色")
图表已保存为: bar_demo.png
plt.bar() 返回值信息:
============================================================
返回值类型: <class 'matplotlib.container.BarContainer'>
子图1矩形对象数量: 6
子图2矩形对象总数: 18
Rectangle对象主要属性:
- get_height(): 获取柱子高度
- get_width(): 获取柱子宽度
- get_x(): 获取柱子x坐标
- get_y(): 获取柱子y坐标
- get_facecolor(): 获取填充颜色
- get_edgecolor(): 获取边缘颜色

plt.hist() - 直方图
plt.hist(x, bins=None, range=None, density=False,
weights=None, cumulative=False, bottom=None,
histtype='bar', align='mid', orientation='vertical',
rwidth=None, log=False, color=None, label=None,
stacked=False, **kwargs)
参数中文说明:
x- 输入数据
bins- 箱子数量或边界(整数、序列或字符串)
range- 数据范围
density- 是否显示概率密度
weights- 权重
cumulative- 是否显示累积分布
bottom- 底部位置
histtype- 类型('bar', 'barstacked', 'step', 'stepfilled')
align- 对齐('left', 'mid', 'right')
orientation- 方向('vertical', 'horizontal')
rwidth- 柱子相对宽度
log- 是否对数刻度
color- 颜色
edgecolor- 边缘颜色
linewidth- 线宽
alpha- 透明度
label- 图例标签
stacked- 是否堆叠
返回值类型:(n, bins, patches)元组
n- 每个箱子的计数值(数组)
bins- 箱子边界(数组)
patches- 图形对象列表
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 创建图形
fig, axes = plt.subplots(2, 2, figsize=(14, 12),
facecolor='#F8F9FA',
# constrained_layout=True
)
# 生成示例数据
np.random.seed(42)
n = 1000
data1 = np.random.normal(0, 1, n) # 正态分布
data2 = np.random.normal(2, 1.5, n) # 另一个正态分布
data3 = np.random.exponential(2, n) # 指数分布
# 子图1:基本直方图
ax1 = axes[0, 0]
# 绘制直方图,获取返回值
n1, bins1, patches1 = ax1.hist(data1, bins=30, # 返回值:计数值、箱子边界、图形对象
color='lightblue',
edgecolor='black',
linewidth=1,
alpha=0.7,
label='正态分布')
# 添加统计信息
mean_val = np.mean(data1)
std_val = np.std(data1)
ax1.axvline(mean_val, color='red', linestyle='--',
linewidth=2, label=f'均值: {mean_val:.2f}')
ax1.axvline(mean_val + std_val, color='green', linestyle=':',
linewidth=1, alpha=0.5, label='±1标准差')
ax1.axvline(mean_val - std_val, color='green', linestyle=':',
linewidth=1, alpha=0.5)
ax1.set_title('1. 基本直方图 (正态分布)', fontsize=12, fontweight='bold')
ax1.set_xlabel('数值', fontsize=10)
ax1.set_ylabel('频数', fontsize=10)
ax1.legend(loc='upper right', fontsize=9)
ax1.grid(True, alpha=0.3)
# 子图2:概率密度直方图
ax2 = axes[0, 1]
# 绘制概率密度直方图
n2, bins2, patches2 = ax2.hist(data1, bins=30, # 返回值
density=True, # 概率密度
color='lightgreen',
edgecolor='black',
linewidth=1,
alpha=0.7,
label='直方图')
# 添加核密度估计
from scipy import stats
kde = stats.gaussian_kde(data1)
x_range = np.linspace(data1.min(), data1.max(), 1000)
ax2.plot(x_range, kde(x_range), 'r-',
linewidth=2, label='KDE')
ax2.set_title('2. 概率密度直方图 + KDE', fontsize=12, fontweight='bold')
ax2.set_xlabel('数值', fontsize=10)
ax2.set_ylabel('概率密度', fontsize=10)
ax2.legend(loc='upper right', fontsize=9)
ax2.grid(True, alpha=0.3)
# 子图3:堆叠直方图
ax3 = axes[1, 0]
# 绘制堆叠直方图
n3, bins3, patches3 = ax3.hist([data1, data2], bins=30, # 多个数据集
stacked=True, # 堆叠
color=['lightblue', 'lightgreen'],
edgecolor='black',
linewidth=1,
alpha=0.7,
label=['分布1', '分布2'])
ax3.set_title('3. 堆叠直方图', fontsize=12, fontweight='bold')
ax3.set_xlabel('数值', fontsize=10)
ax3.set_ylabel('频数', fontsize=10)
ax3.legend(loc='upper right', fontsize=9)
ax3.grid(True, alpha=0.3)
# 子图4:累积分布直方图
ax4 = axes[1, 1]
# 绘制累积分布直方图
n4, bins4, patches4 = ax4.hist(data1, bins=30, # 返回值
cumulative=True, # 累积
density=True, # 概率密度
histtype='step', # 线型
linewidth=2,
color='red',
label='CDF')
# 添加理论CDF
x_range = np.linspace(data1.min(), data1.max(), 1000)
cdf = stats.norm.cdf(x_range, mean_val, std_val)
ax4.plot(x_range, cdf, 'b--',
linewidth=1.5, alpha=0.7, label='理论CDF')
# 添加百分位数
percentiles = [25, 50, 75, 90]
for p in percentiles:
percentile_val = np.percentile(data1, p)
ax4.axvline(percentile_val, color='green',
linestyle=':', linewidth=1, alpha=0.7)
ax4.text(percentile_val, 0.5, f'{p}%',
ha='center', va='bottom', rotation=90,
fontsize=8, fontweight='bold')
ax4.set_title('4. 累积分布直方图 (CDF)', fontsize=12, fontweight='bold')
ax4.set_xlabel('数值', fontsize=10)
ax4.set_ylabel('累积概率', fontsize=10)
ax4.legend(loc='upper left', fontsize=9)
ax4.grid(True, alpha=0.3)
# 添加总标题
fig.suptitle('plt.hist() 直方图函数详解',
fontsize=16, fontweight='bold', y=0.98)
plt.show()
# 打印返回值信息
print("plt.hist() 返回值信息:")
print("="*60)
print(f"返回值类型: tuple (长度为3)")
print(f" n (计数值) 类型: {type(n1)}, 形状: {n1.shape}")
print(f" bins (箱子边界) 类型: {type(bins1)}, 形状: {bins1.shape}")
print(f" patches (图形对象) 类型: {type(patches1)}")
print(f" patches 数量: {len(patches1)}")
print("\n子图1直方图统计信息:")
print(f" 数据点数: {len(data1)}")
print(f" 箱子数量: {len(bins1)-1}")
print(f" 计数值总和: {n1.sum()}")
print(f" 第一个箱子范围: [{bins1[0]:.2f}, {bins1[1]:.2f}]")
print(f" 第一个箱子计数值: {n1[0]}")
plt.hist() 返回值信息:
============================================================
返回值类型: tuple (长度为3)
n (计数值) 类型: <class 'numpy.ndarray'>, 形状: (30,)
bins (箱子边界) 类型: <class 'numpy.ndarray'>, 形状: (31,)
patches (图形对象) 类型: <class 'matplotlib.container.BarContainer'>
patches 数量: 30
子图1直方图统计信息:
数据点数: 1000
箱子数量: 30
计数值总和: 1000.0
第一个箱子范围: [-3.24, -3.00]
第一个箱子计数值: 1.0

plt.pie() - 饼图
plt.pie(x, explode=None, labels=None, colors=None,
autopct=None, pctdistance=0.6, shadow=False,
labeldistance=1.1, startangle=90, radius=1,
counterclock=True, wedgeprops=None, textprops=None,
center=(0, 0), frame=False, rotatelabels=False,
normalize=True, hatch=None, data=None)
参数中文说明:
x- 扇区大小
explode- 突出显示(长度与x相同的序列)
labels- 扇区标签
colors- 颜色列表
autopct- 百分比格式字符串或函数
pctdistance- 百分比文字距圆心距离
shadow- 是否显示阴影
labeldistance- 标签距圆心距离
startangle- 起始角度
radius- 半径
counterclock- 是否逆时针
wedgeprops- 扇区属性字典
textprops- 文本属性字典
center- 圆心坐标
frame- 是否显示框架
rotatelabels- 是否旋转标签
normalize- 是否标准化为1
hatch- 填充图案
返回值类型:(patches, texts, autotexts)元组
patches- 扇形对象列表
texts- 标签文本对象列表
autotexts- 百分比文本对象列表
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 创建图形
fig, axes = plt.subplots(2, 2, figsize=(14, 12),
facecolor='#F8F9FA',
#constrained_layout=True
)
# 数据准备
categories = ['电子产品', '服装', '食品', '住房', '交通', '娱乐', '教育', '医疗']
expenses = [1200, 800, 1500, 3000, 700, 500, 900, 600]
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4',
'#FFEAA7', '#DDA0DD', '#F0E68C', '#87CEEB']
# 子图1:基本饼图
ax1 = axes[0, 0]
# 绘制饼图,获取返回值
patches1, texts1, autotexts1 = ax1.pie(
expenses[:5], # 前5个数据
labels=categories[:5],
colors=colors[:5],
autopct='%1.1f%%', # 百分比格式
startangle=90, # 起始角度
shadow=True, # 阴影
labeldistance=1.1, # 标签距离
pctdistance=0.8, # 百分比距离
explode=(0.1, 0, 0, 0, 0) # 突出第一块
)
# 设置百分比文本样式
for autotext in autotexts1:
autotext.set_color('white')
autotext.set_fontweight('bold')
autotext.set_fontsize(10)
ax1.set_title('1. 基本饼图 (带突出和阴影)', fontsize=12, fontweight='bold')
# 子图2:环形图
ax2 = axes[0, 1]
# 绘制环形图
patches2, texts2, autotexts2 = ax2.pie(
expenses,
labels=categories,
colors=colors,
autopct='%1.1f%%',
startangle=90,
pctdistance=0.85, # 百分比靠近边缘
wedgeprops=dict(width=0.3, edgecolor='black') # 控制环形图厚度
)
# 设置百分比文本样式
for autotext in autotexts2:
autotext.set_color('black')
autotext.set_fontweight('bold')
autotext.set_fontsize(9)
# 添加中心圆
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
ax2.add_artist(centre_circle)
# 添加中心文本
ax2.text(0, 0, '总消费\n构成',
ha='center', va='center',
fontsize=12, fontweight='bold')
ax2.set_title('2. 环形图 (甜甜圈图)', fontsize=12, fontweight='bold')
# 子图3:堆叠饼图
ax3 = axes[1, 0]
# 模拟两年数据
expenses_2023 = expenses
expenses_2024 = [int(e * 1.2) for e in expenses] # 增长20%
# 绘制外层环 (2024)
patches3_outer, texts3_outer, autotexts3_outer = ax3.pie(
expenses_2024,
radius=1.2, # 外环半径
colors=colors,
autopct=lambda pct: f'{pct:.1f}%',
pctdistance=0.9, # 百分比在外环外侧
wedgeprops=dict(width=0.3, edgecolor='black')
)
# 绘制内层环 (2023)
patches3_inner, _, autotexts3_inner = ax3.pie(
expenses_2023,
radius=0.9, # 内环半径
colors=[c for c in colors], # 相同颜色
autopct=lambda pct: f'{pct:.1f}%',
pctdistance=0.7, # 百分比在内环内侧
wedgeprops=dict(width=0.3, edgecolor='black')
)
# 设置百分比文本样式
for autotext in autotexts3_outer + autotexts3_inner:
autotext.set_color('black')
autotext.set_fontweight('bold')
autotext.set_fontsize(8)
# 添加中心圆
centre_circle = plt.Circle((0, 0), 0.6, fc='white')
ax3.add_artist(centre_circle)
# 添加图例
ax3.legend(patches3_outer, categories,
title="消费类别",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1),
fontsize=8)
ax3.set_title('3. 堆叠饼图 (内:2023, 外:2024)', fontsize=12, fontweight='bold')
# 子图4:自定义饼图
ax4 = axes[1, 1]
# 自定义百分比格式函数
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
return f'{pct:.1f}%\n({val}元)'
return my_autopct
# 绘制自定义饼图
patches4, texts4, autotexts4 = ax4.pie(
expenses,
labels=categories,
colors=colors,
autopct=make_autopct(expenses), # 自定义格式
startangle=180, # 从180度开始
counterclock=False, # 顺时针
rotatelabels=True, # 旋转标签
textprops=dict(rotation_mode='anchor', va='center', ha='center'),
wedgeprops=dict(edgecolor='black', linewidth=1)
)
# 设置文本样式
for autotext in autotexts4:
autotext.set_color('white')
autotext.set_fontweight('bold')
autotext.set_fontsize(8)
for text in texts4:
text.set_fontsize(9)
text.set_fontweight('bold')
ax4.set_title('4. 自定义饼图 (旋转标签)', fontsize=12, fontweight='bold')
# 添加总标题
fig.suptitle('plt.pie() 饼图函数详解',
fontsize=16, fontweight='bold', y=0.98)
plt.show()
# 打印返回值信息
print("plt.pie() 返回值信息:")
print("="*60)
print(f"返回值类型: tuple (长度为3)")
print(f" patches (扇形对象) 类型: {type(patches1)}")
print(f" patches 数量: {len(patches1)}")
print(f" texts (标签对象) 类型: {type(texts1)}")
print(f" texts 数量: {len(texts1)}")
print(f" autotexts (百分比对象) 类型: {type(autotexts1)}")
print(f" autotexts 数量: {len(autotexts1)}")
print("\n饼图统计信息:")
print(f" 总扇区数: {len(expenses)}")
print(f" 总金额: {sum(expenses)} 元")
print(f" 最大扇区: {categories[expenses.index(max(expenses))]} ({max(expenses)}元, {max(expenses)/sum(expenses)*100:.1f}%)")
print(f" 最小扇区: {categories[expenses.index(min(expenses))]} ({min(expenses)}元, {min(expenses)/sum(expenses)*100:.1f}%)")
plt.pie() 返回值信息:
============================================================
返回值类型: tuple (长度为3)
patches (扇形对象) 类型: <class 'list'>
patches 数量: 5
texts (标签对象) 类型: <class 'list'>
texts 数量: 5
autotexts (百分比对象) 类型: <class 'list'>
autotexts 数量: 5
饼图统计信息:
总扇区数: 8
总金额: 9200 元
最大扇区: 住房 (3000元, 32.6%)
最小扇区: 娱乐 (500元, 5.4%)

plt.contour() 等高线图
plt.contour([X, Y], Z, levels=10,
colors=None, alpha=None, linewidths=None,
linestyles=None, antialiased=None, extent=None,
cmap=None, norm=None, vmin=None, vmax=None,
origin=None, **kwargs)
X Y:2D数组 网格坐标(形状同Z)
Z: 2D数组 高度值数组(形状为(n,m))
levels: int/列表/数组、等高线条数或具体层级值
colors=None str/列表 等高线颜色
alpha=None float 透明度(0-1)
linewidths=None float/列表 线宽
linestyles=None str/列表 线型
antialiased=None bool 抗锯齿
extent=None tuple 数据范围(xmin,xmax,ymin,ymax)
cmap=None str/Colormap 颜色映射
norm=None Normalize 数据归一化
vmin=None float 颜色映射最小值
vmax=None float 颜色映射最大值
origin=None str 原点位置('upper'或'lower')
**kwarg
返回值: matplotlib.contour.QuadContourSet对象
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from matplotlib.colors import LogNorm, Normalize, BoundaryNorm
from matplotlib.ticker import LogLocator, MultipleLocator
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 实际应用示例:地形分析和气象图
fig, axes = plt.subplots(1, 3, figsize=(18, 5), facecolor='#F8F9FA')
# 示例1:地形等高线
ax1 = axes[0]
# 模拟地形数据
x_terrain = np.linspace(-10, 10, 200)
y_terrain = np.linspace(-10, 10, 200)
X_terrain, Y_terrain = np.meshgrid(x_terrain, y_terrain)
# 创建有山有谷的地形
Z_terrain = (3 * np.exp(-(X_terrain**2 + Y_terrain**2)/20) + # 主峰
2 * np.exp(-((X_terrain-5)**2 + (Y_terrain+5)**2)/10) + # 次峰
1.5 * np.exp(-((X_terrain+5)**2 + (Y_terrain-5)**2)/15) - # 山谷
2 * np.exp(-((X_terrain+3)**2 + (Y_terrain+3)**2)/8))
# 计算等高线间距
z_min, z_max = Z_terrain.min(), Z_terrain.max()
terrain_levels = np.linspace(z_min, z_max, 15)
contour_terrain = ax1.contour(
X_terrain, Y_terrain, Z_terrain,
levels=terrain_levels,
cmap='terrain',
linewidths=1.2,
alpha=0.9
)
# 添加高度标签
ax1.clabel(contour_terrain,
inline=True,
fontsize=8,
colors='black',
fmt='%.1f')
# 标记最高点
max_idx = np.unravel_index(Z_terrain.argmax(), Z_terrain.shape)
ax1.scatter(X_terrain[max_idx], Y_terrain[max_idx],
color='red',
s=100,
marker='^',
edgecolors='black',
linewidth=2,
label=f'最高点: {Z_terrain[max_idx]:.2f}',
zorder=5)
# 标记最低点
min_idx = np.unravel_index(Z_terrain.argmin(), Z_terrain.shape)
ax1.scatter(X_terrain[min_idx], Y_terrain[min_idx],
color='blue',
s=100,
marker='v',
edgecolors='black',
linewidth=2,
label=f'最低点: {Z_terrain[min_idx]:.2f}',
zorder=5)
ax1.set_title('地形等高线图', fontsize=12, fontweight='bold')
ax1.set_xlabel('东-西方向 (km)', fontsize=10)
ax1.set_ylabel('北-南方向 (km)', fontsize=10)
ax1.legend(loc='upper right', fontsize=8)
ax1.grid(True, alpha=0.3, linestyle=':')
ax1.set_aspect('equal')
# 示例2:温度分布图
ax2 = axes[1]
# 模拟温度分布
x_temp = np.linspace(0, 24, 100) # 24小时
y_temp = np.linspace(0, 30, 100) # 30天
X_temp, Y_temp = np.meshgrid(x_temp, y_temp)
# 温度函数:日变化 + 季节变化
Z_temp = (20 + 10 * np.sin(2*np.pi*Y_temp/30) + # 季节变化
5 * np.sin(2*np.pi*X_temp/24) + # 日变化
2 * np.random.randn(*X_temp.shape) * 0.1) # 噪声
# 温度等高线
temp_levels = np.arange(10, 36, 2) # 10°C 到 35°C,间隔2°C
contour_temp = ax2.contour(
X_temp, Y_temp, Z_temp,
levels=temp_levels,
colors='darkred',
linewidths=1.5,
alpha=0.8,
linestyles='-'
)
# 添加温度标签
ax2.clabel(contour_temp,
inline=True,
fontsize=9,
colors='darkred',
fmt='%d°C')
# 标记最高温和最低温
temp_max_idx = np.unravel_index(Z_temp.argmax(), Z_temp.shape)
temp_min_idx = np.unravel_index(Z_temp.argmin(), Z_temp.shape)
ax2.scatter(X_temp[temp_max_idx], Y_temp[temp_max_idx],
color='red',
s=80,
marker='o',
edgecolors='black',
linewidth=2,
label=f'最高温: {Z_temp[temp_max_idx]:.1f}°C',
zorder=5)
ax2.scatter(X_temp[temp_min_idx], Y_temp[temp_min_idx],
color='blue',
s=80,
marker='o',
edgecolors='black',
linewidth=2,
label=f'最低温: {Z_temp[temp_min_idx]:.1f}°C',
zorder=5)
ax2.set_title('温度分布等高线图', fontsize=12, fontweight='bold')
ax2.set_xlabel('时间 (小时)', fontsize=10)
ax2.set_ylabel('天数', fontsize=10)
ax2.legend(loc='upper right', fontsize=8)
ax2.grid(True, alpha=0.3, linestyle=':')
# 示例3:气压等压线
ax3 = axes[2]
# 模拟气压分布
x_pressure = np.linspace(-1000, 1000, 150) # 公里
y_pressure = np.linspace(-1000, 1000, 150)
X_pressure, Y_pressure = np.meshgrid(x_pressure, y_pressure)
# 模拟高气压和低气压系统
Z_pressure = (1013.25 - # 标准大气压
20 * np.exp(-(X_pressure**2 + Y_pressure**2)/500000) + # 高气压
15 * np.exp(-((X_pressure-300)**2 + (Y_pressure+400)**2)/300000) - # 低气压
10 * np.exp(-((X_pressure+400)**2 + (Y_pressure-300)**2)/400000))
# 等压线
pressure_levels = np.arange(980, 1030, 2) # 980-1030 hPa,间隔2 hPa
contour_pressure = ax3.contour(
X_pressure, Y_pressure, Z_pressure,
levels=pressure_levels,
colors='navy',
linewidths=1.2,
alpha=0.9,
linestyles=['-', '--', '-.', ':']*5 # 循环使用线型
)
# 添加气压标签
ax3.clabel(contour_pressure,
inline=True,
fontsize=8,
colors='navy',
fmt='%d hPa')
# 标记高压中心和低压中心
# 找到局部极大值(高压中心)
from scipy.ndimage import maximum_filter
neighborhood_size = 20
data_max = maximum_filter(Z_pressure, neighborhood_size)
maxima = (Z_pressure == data_max)
high_pressure_points = np.argwhere(maxima)
# 标记高压中心
for idx in high_pressure_points[:3]: # 前3个高压中心
i, j = idx
ax3.scatter(X_pressure[i, j], Y_pressure[i, j],
color='red',
s=100,
marker='^',
edgecolors='black',
linewidth=2,
label='高压中心' if idx[0]==high_pressure_points[0][0] else "",
zorder=5)
# 标记低压中心
data_min = -maximum_filter(-Z_pressure, neighborhood_size)
minima = (Z_pressure == data_min)
low_pressure_points = np.argwhere(minima)
# 标记低压中心
for idx in low_pressure_points[:3]: # 前3个低压中心
i, j = idx
ax3.scatter(X_pressure[i, j], Y_pressure[i, j],
color='blue',
s=100,
marker='v',
edgecolors='black',
linewidth=2,
label='低压中心' if idx[0]==low_pressure_points[0][0] else "",
zorder=5)
ax3.set_title('气压等压线图', fontsize=12, fontweight='bold')
ax3.set_xlabel('经度方向 (km)', fontsize=10)
ax3.set_ylabel('纬度方向 (km)', fontsize=10)
ax3.legend(loc='upper right', fontsize=8)
ax3.grid(True, alpha=0.3, linestyle=':')
ax3.set_aspect('equal')
plt.tight_layout()
# 保存图表到文件,避免显示阻塞
plt.savefig('contour_applications.png', dpi=100, bbox_inches='tight')
print("图表已保存为: contour_applications.png")
# 关闭图表
plt.close()

颜色速查表
| 字符 |
颜色 |
中文 |
RGB值 |
示例 |
'b' |
blue |
蓝色 |
(0,0,1) |
plt.plot(x, y, 'b-') |
'g' |
green |
绿色 |
(0,0.5,0) |
plt.plot(x, y, 'g-') |
'r' |
red |
红色 |
(1,0,0) |
plt.plot(x, y, 'r-') |
'c' |
cyan |
青色 |
(0,0.75,0.75) |
plt.plot(x, y, 'c-') |
'm' |
magenta |
洋红 |
(0.75,0,0.75) |
plt.plot(x, y, 'm-') |
'y' |
yellow |
黄色 |
(0.75,0.75,0) |
plt.plot(x, y, 'y-') |
'k' |
black |
黑色 |
(0,0,0) |
plt.plot(x, y, 'k-') |
'w' |
white |
白色 |
(1,1,1) |
plt.plot(x, y, 'w-') |
颜色表示方法
# 1. 单字符表示
plt.plot(x, y, 'b-') # 蓝色实线
# 2. 颜色名称表示
plt.plot(x, y, color='red')
plt.plot(x, y, color='steelblue')
# 3. 十六进制表示
plt.plot(x, y, color='#FF0000') # 红色
plt.plot(x, y, color='#00FF00') # 绿色
plt.plot(x, y, color='#0000FF') # 蓝色
plt.plot(x, y, color='#FF6B6B') # 浅红色
plt.plot(x, y, color='#4ECDC4') # 青绿色
# 4. RGB元组表示 (0-1)
plt.plot(x, y, color=(1, 0, 0)) # 红色
plt.plot(x, y, color=(0, 1, 0)) # 绿色
plt.plot(x, y, color=(0, 0, 1)) # 蓝色
plt.plot(x, y, color=(0.5, 0.2, 0.8)) # 紫色
# 5. RGBA元组表示 (带透明度)
plt.plot(x, y, color=(1, 0, 0, 0.5)) # 半透明红色
plt.plot(x, y, color=(0, 1, 0, 0.3)) # 30%透明度绿色
# 6. 灰度表示
plt.plot(x, y, color='0.5') # 50%灰度
plt.plot(x, y, color='0.8') # 80%灰度
plt.plot(x, y, color='0.2') # 20%灰度
线型速查表
基本线型
| 字符 |
名称 |
中文 |
示例 |
图示 |
'-' |
solid line style |
实线 |
plt.plot(x, y, '-') |
───────── |
'--' |
dashed line style |
虚线 |
plt.plot(x, y, '--') |
─ ─ ─ ─ |
'-.' |
dash-dot line style |
点划线 |
plt.plot(x, y, '-.') |
─·─·─· |
':' |
dotted line style |
点线 |
plt.plot(x, y, ':') |
······· |
线型控制参数
# 1. 通过linestyle参数控制
plt.plot(x, y, linestyle='-') # 实线
plt.plot(x, y, linestyle='--') # 虚线
plt.plot(x, y, linestyle='-.') # 点划线
plt.plot(x, y, linestyle=':') # 点线
plt.plot(x, y, linestyle='') # 无线
plt.plot(x, y, linestyle='None') # 无线
# 2. 快捷写法(格式字符串)
plt.plot(x, y, 'b-') # 蓝色实线
plt.plot(x, y, 'r--') # 红色虚线
plt.plot(x, y, 'g-.') # 绿色点划线
plt.plot(x, y, 'y:') # 黄色点线
# 3. 自定义虚线模式
plt.plot(x, y, linestyle=(0, (1, 1))) # 等长的点和空白
plt.plot(x, y, linestyle=(0, (5, 5))) # 长虚线
plt.plot(x, y, linestyle=(0, (5, 1))) # 长虚线与短空白
plt.plot(x, y, linestyle=(0, (3, 1, 1, 1))) # 复杂模式
plt.plot(x, y, linestyle=(0, (3, 5, 1, 5))) # 自定义模式
自定义虚线模式说明
# 格式: (offset, on_off_sequence)
# offset: 起始偏移量
# on_off_sequence: 实线和空白的交替长度序列
patterns = {
'简单虚线': (0, (5, 5)), # 5点实线,5点空白
'密集虚线': (0, (2, 2)), # 2点实线,2点空白
'点划线': (0, (5, 2, 1, 2)), # 5实,2空,1实,2空
'双点划线': (0, (5, 2, 1, 2, 1, 2)), # 5实,2空,1实,2空,1实,2空
'自定义1': (0, (3, 1, 1, 1)), # 3实,1空,1实,1空
'自定义2': (0, (3, 5, 1, 5, 1, 5)), # 3实,5空,1实,5空,1实,5空
'随机': (0, (3, 2, 1, 2, 4, 2)), # 随机模式
}
标记(点)形状速查表
基本标记形状
| 字符 |
名称 |
中文 |
示例 |
图示 |
'.' |
point marker |
点 |
plt.plot(x, y, '.') |
• |
',' |
pixel marker |
像素 |
plt.plot(x, y, ',') |
▫ |
'o' |
circle marker |
圆圈 |
plt.plot(x, y, 'o') |
○ |
'v' |
triangle_down marker |
下三角 |
plt.plot(x, y, 'v') |
▽ |
'^' |
triangle_up marker |
上三角 |
plt.plot(x, y, '^') |
△ |
'<' |
triangle_left marker |
左三角 |
plt.plot(x, y, '<') |
◁ |
'>' |
triangle_right marker |
右三角 |
plt.plot(x, y, '>') |
▷ |
'1' |
tri_down marker |
三角1 |
plt.plot(x, y, '1') |
⟁ |
'2' |
tri_up marker |
三角2 |
plt.plot(x, y, '2') |
⟁ |
'3' |
tri_left marker |
三角3 |
plt.plot(x, y, '3') |
⟁ |
'4' |
tri_right marker |
三角4 |
plt.plot(x, y, '4') |
⟁ |
's' |
square marker |
方形 |
plt.plot(x, y, 's') |
□ |
'p' |
pentagon marker |
五边形 |
plt.plot(x, y, 'p') |
⬠ |
'*' |
star marker |
星形 |
plt.plot(x, y, '*') |
✶ |
'h' |
hexagon1 marker |
六边形1 |
plt.plot(x, y, 'h') |
⬢ |
'H' |
hexagon2 marker |
六边形2 |
plt.plot(x, y, 'H') |
⬢ |
'+' |
plus marker |
加号 |
plt.plot(x, y, '+') |
+ |
'x' |
x marker |
叉号 |
plt.plot(x, y, 'x') |
× |
'D' |
diamond marker |
菱形 |
plt.plot(x, y, 'D') |
◇ |
'd' |
thin_diamond marker |
细菱形 |
plt.plot(x, y, 'd') |
◆ |
'|' |
vline marker |
竖线 |
plt.plot(x, y, '|') |
| |
'_' |
hline marker |
横线 |
plt.plot(x, y, '_') |
_ |
标记控制参数
# 1. 通过marker参数控制
plt.plot(x, y, marker='o') # 圆圈
plt.plot(x, y, marker='s') # 方形
plt.plot(x, y, marker='^') # 上三角
plt.plot(x, y, marker='D') # 菱形
plt.plot(x, y, marker='*') # 星形
plt.plot(x, y, marker='+') # 加号
plt.plot(x, y, marker='x') # 叉号
plt.plot(x, y, marker='p') # 五边形
plt.plot(x, y, marker='h') # 六边形
plt.plot(x, y, marker='.') # 点
plt.plot(x, y, marker='') # 无标记
plt.plot(x, y, marker='None') # 无标记
# 2. 快捷写法(格式字符串)
plt.plot(x, y, 'ro') # 红色圆圈
plt.plot(x, y, 'bs') # 蓝色方形
plt.plot(x, y, 'g^') # 绿色上三角
plt.plot(x, y, 'kD') # 黑色菱形
plt.plot(x, y, 'm*') # 洋红星形
plt.plot(x, y, 'c+') # 青色加号
plt.plot(x, y, 'yx') # 黄色叉号
# 3. 标记大小控制
plt.plot(x, y, marker='o', markersize=5) # 小圆圈
plt.plot(x, y, marker='o', markersize=10) # 中圆圈
plt.plot(x, y, marker='o', markersize=20) # 大圆圈
plt.plot(x, y, marker='o', markersize=50) # 超大圆圈
# 4. 标记颜色控制
plt.plot(x, y, marker='o', markerfacecolor='red') # 红色填充
plt.plot(x, y, marker='o', markerfacecolor='blue') # 蓝色填充
plt.plot(x, y, marker='o', markerfacecolor='green') # 绿色填充
plt.plot(x, y, marker='o', markerfacecolor='none') # 无填充
plt.plot(x, y, marker='o', markeredgecolor='black') # 黑色边框
plt.plot(x, y, marker='o', markeredgecolor='white') # 白色边框
plt.plot(x, y, marker='o', markeredgecolor='red') # 红色边框
plt.plot(x, y, marker='o', markeredgewidth=1) # 边框线宽1
plt.plot(x, y, marker='o', markeredgewidth=2) # 边框线宽2
plt.plot(x, y, marker='o', markeredgewidth=3) # 边框线宽3
组合格式速查表
格式字符串语法
# 格式: [颜色][标记][线型]
plt.plot(x, y, 'ro-') # 红色圆圈实线
plt.plot(x, y, 'bs--') # 蓝色方形虚线
plt.plot(x, y, 'g^-.') # 绿色上三角点划线
plt.plot(x, y, 'kD:') # 黑色菱形点线
plt.plot(x, y, 'm*') # 洋红星形(无线,只有标记)
plt.plot(x, y, 'c+') # 青色加号(无线,只有标记)
plt.plot(x, y, 'yx') # 黄色叉号(无线,只有标记)
plt.plot(x, y, 'b-') # 蓝色实线(无标记)
plt.plot(x, y, 'r--') # 红色虚线(无标记)
plt.plot(x, y, 'g-.') # 绿色点划线(无标记)
plt.plot(x, y, 'k:') # 黑色点线(无标记)
# 组合示例
combinations = {
'点线图': 'b.-', # 蓝色点实线
'散点图': 'ro', # 红色圆圈(无线)
'带标记的虚线': 'g^--', # 绿色上三角虚线
'星形点划线': 'm*-.', # 洋红星形点划线
'菱形点线': 'kD:', # 黑色菱形点线
'加号实线': 'c+-', # 青色加号实线
'方形虚线': 'ys--', # 黄色方形虚线
}
常用组合推荐
| 用途 |
推荐格式 |
说明 |
| 主要数据线 |
'b-' |
蓝色实线,清晰易读 |
| 对比数据线 |
'r--' |
红色虚线,对比明显 |
| 次要数据线 |
'g-.' |
绿色点划线,层次分明 |
| 参考线 |
'k:' |
黑色点线,不喧宾夺主 |
| 数据点 |
'ro' |
红色圆圈,醒目明显 |
| 异常点 |
'r*' |
红色星形,特别标记 |
| 趋势线 |
'b--' |
蓝色虚线,表示趋势 |
| 预测线 |
'g:' |
绿色点线,表示预测 |
| 散点图 |
'bo' |
蓝色圆圈,经典散点 |
| 分类点 |
'rs', 'g^', 'bo' |
不同形状区分类别 |
快速参考表
最常用组合
| 场景 |
推荐格式 |
说明 |
| 主曲线 |
'b-' |
蓝色实线 |
| 对比曲线 |
'r--' |
红色虚线 |
| 参考线 |
'k:' |
黑色点线 |
| 数据点 |
'ro' |
红色圆圈 |
| 散点图 |
'bo' |
蓝色圆圈 |
| 分类1 |
'r^-' |
红色上三角实线 |
| 分类2 |
'bs--' |
蓝色方形虚线 |
| 分类3 |
'gD-.' |
绿色菱形点划线 |
| 异常点 |
'r*' |
红色星形 |
| 预测线 |
'c:' |
青色点线 |
专业配色方案
# 科学论文配色
science_colors = {
'控制组': '#1f77b4', # 蓝色
'实验组': '#ff7f0e', # 橙色
'对照组': '#2ca02c', # 绿色
'参考线': '#7f7f7f', # 灰色
}
# 商业报告配色
business_colors = {
'收入': '#4ECDC4', # 青绿
'成本': '#FF6B6B', # 红色
'利润': '#45B7D1', # 蓝色
'预测': '#96CEB4', # 浅绿
}
# 网页安全色
web_safe_colors = [
'#FF0000', '#00FF00', '#0000FF', # RGB
'#FFFF00', '#00FFFF', '#FF00FF', # CMY
'#C0C0C0', '#808080', '#800000', # 灰色系
'#808000', '#008000', '#800080', # 混合色
'#008080', '#000080', '#000000', # 深色系
]
无障碍设计颜色
# 色盲友好配色
colorblind_friendly = {
'类别1': '#E69F00', # 橙色
'类别2': '#56B4E9', # 蓝色
'类别3': '#009E73', # 绿色
'类别4': '#F0E442', # 黄色
'类别5': '#0072B2', # 深蓝
'类别6': '#D55E00', # 红棕
'类别7': '#CC79A7', # 粉紫
}
# 打印友好配色(灰度)
print_friendly = {
'深色': '#000000', # 黑色
'中深': '#666666', # 深灰
'中等': '#999999', # 中灰
'中浅': '#CCCCCC', # 浅灰
'浅色': '#FFFFFF', # 白色
}