github star gitee star atomgit star PyPI Downloads AI 编程 AI 交流群

大家好,我是正在实战各种AI项目的程序员晚枫。

欢迎来到数据可视化部分!

一图胜千言。掌握数据可视化,你能把枯燥的数字变成直观的图表,让数据自己说话。

今天从Python最基础的绘图库Matplotlib开始。


快速开始

安装与导入

1
pip install matplotlib
1
2
3
4
5
import matplotlib.pyplot as plt
import numpy as np

# 在Jupyter中显示图形
%matplotlib inline

第一张图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 准备数据
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

# 创建图形
plt.plot(x, y)

# 添加标题和标签
plt.title('平方数')
plt.xlabel('x')
plt.ylabel('y')

# 显示图形
plt.show()

基本图表类型

折线图(Line Plot)

1
2
3
4
5
6
7
8
9
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title('正弦波')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True) # 添加网格
plt.show()

散点图(Scatter Plot)

1
2
3
4
5
6
x = np.random.randn(100)
y = np.random.randn(100)

plt.scatter(x, y, alpha=0.5) # alpha设置透明度
plt.title('随机散点')
plt.show()

柱状图(Bar Chart)

1
2
3
4
5
6
7
8
9
10
11
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]

plt.bar(categories, values)
plt.title('类别对比')
plt.ylabel('数值')
plt.show()

# 水平柱状图
plt.barh(categories, values)
plt.show()

直方图(Histogram)

1
2
3
4
5
6
7
data = np.random.randn(1000)

plt.hist(data, bins=30, edgecolor='black')
plt.title('数据分布')
plt.xlabel('值')
plt.ylabel('频数')
plt.show()

饼图(Pie Chart)

1
2
3
4
5
6
7
sizes = [30, 20, 25, 25]
labels = ['A', 'B', 'C', 'D']
colors = ['red', 'blue', 'green', 'yellow']

plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
plt.title('占比分布')
plt.show()

样式美化

线条样式

1
2
3
4
5
6
7
8
x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x), 'b-', linewidth=2, label='sin') # 蓝色实线
plt.plot(x, np.cos(x), 'r--', linewidth=2, label='cos') # 红色虚线
plt.plot(x, np.tan(x), 'g:', linewidth=2, label='tan') # 绿色点线

plt.legend() # 显示图例
plt.show()

颜色与标记

1
2
3
4
5
# 颜色缩写:b蓝 g绿 r红 c青 m紫 y黄 k黑 w白
# 标记:o圆点 s方形 ^三角形 *星形 +加号

plt.plot(x, y, 'ro-') # 红色圆点实线
plt.plot(x, y, 'gs--') # 绿色方形虚线

中文显示

1
2
3
4
5
6
7
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题

plt.title('中文标题')
plt.xlabel('横轴')
plt.ylabel('纵轴')

多子图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 方式1:subplot
plt.subplot(2, 2, 1) # 2行2列的第1个
plt.plot(x, np.sin(x))
plt.title('sin')

plt.subplot(2, 2, 2) # 第2个
plt.plot(x, np.cos(x))
plt.title('cos')

plt.subplot(2, 2, 3) # 第3个
plt.plot(x, np.tan(x))
plt.title('tan')

plt.subplot(2, 2, 4) # 第4个
plt.plot(x, x**2)
plt.title('x²')

plt.tight_layout() # 自动调整布局
plt.show()

# 方式2:面向对象(推荐)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('sin')

axes[0, 1].plot(x, np.cos(x))
axes[0, 1].set_title('cos')

axes[1, 0].plot(x, np.tan(x))
axes[1, 0].set_title('tan')

axes[1, 1].plot(x, x**2)
axes[1, 1].set_title('x²')

plt.tight_layout()
plt.show()

保存图片

1
2
3
4
5
6
7
8
# 保存为PNG
plt.savefig('chart.png', dpi=300, bbox_inches='tight')

# 保存为PDF(矢量图)
plt.savefig('chart.pdf', bbox_inches='tight')

# 保存为SVG(网页用)
plt.savefig('chart.svg')

实战:销售数据可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 模拟月度销售数据
months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales = [120, 150, 180, 140, 200, 220]
profit = [20, 30, 45, 25, 50, 60]

# 创建图形
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# 左图:销售额趋势
ax1.plot(months, sales, 'bo-', linewidth=2, markersize=8)
ax1.set_title('月度销售额趋势', fontsize=14)
ax1.set_xlabel('月份')
ax1.set_ylabel('销售额(万元)')
ax1.grid(True, alpha=0.3)

# 添加数据标签
for i, v in enumerate(sales):
ax1.text(i, v + 5, str(v), ha='center')

# 右图:销售额vs利润对比
x = np.arange(len(months))
width = 0.35

ax2.bar(x - width/2, sales, width, label='销售额', color='skyblue')
ax2.bar(x + width/2, profit, width, label='利润', color='orange')

ax2.set_title('销售额与利润对比', fontsize=14)
ax2.set_xlabel('月份')
ax2.set_ylabel('金额(万元)')
ax2.set_xticks(x)
ax2.set_xticklabels(months)
ax2.legend()

plt.tight_layout()
plt.savefig('sales_report.png', dpi=300, bbox_inches='tight')
plt.show()

print("图表已保存为 sales_report.png")

性能对比:Matplotlib vs Excel vs 其他库

工具10万点散点图自动化自定义程度中文支持
Excel5秒手动原生
Matplotlib0.5秒代码极高需配置
Seaborn0.5秒代码需配置
Plotly2秒代码原生

进阶用法

双Y轴图表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fig, ax1 = plt.subplots(figsize=(12, 6))

# 左Y轴:销售额
ax1.bar(months, sales, alpha=0.6, label='销售额')
ax1.set_ylabel('销售额 (万元)', color='blue')

# 右Y轴:增长率
ax2 = ax1.twinx()
ax2.plot(months, growth_rate, 'r-o', label='增长率')
ax2.set_ylabel('增长率 (%)', color='red')

# 合并图例
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')

子图布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 2×2子图
fig, axes = plt.subplots(2, 2, figsize=(14, 10))

axes[0, 0].plot(x, y1) # 折线图
axes[0, 0].set_title('趋势图')

axes[0, 1].scatter(x, y2) # 散点图
axes[0, 1].set_title('散点图')

axes[1, 0].bar(categories, values) # 柱状图
axes[1, 0].set_title('柱状图')

axes[1, 1].hist(data, bins=30) # 直方图
axes[1, 1].set_title('分布图')

plt.tight_layout() # 自动调整间距

避坑指南

❌ 坑1:中文显示方块

1
2
3
4
5
6
7
8
9
# 方案1:全局设置
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # Mac
plt.rcParams['axes.unicode_minus'] = False # 负号正常显示

# 方案2:只对当前图设置
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='/path/to/SimHei.ttf')
plt.title('中文标题', fontproperties=font)

❌ 坑2:图表不显示

1
2
3
4
5
6
# 在脚本中需要plt.show()
plt.plot([1,2,3])
plt.show() # 必须调用

# 在Jupyter中推荐
%matplotlib inline # 内嵌显示

❌ 坑3:savefig空白

1
2
3
4
5
6
# savefig必须在show之前调用
plt.plot([1,2,3])
plt.savefig('chart.png', dpi=150, bbox_inches='tight') # 先保存
plt.show() # 再显示

# bbox_inches='tight' 防止标签被裁剪

实战案例:电商月度销售可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

# 模拟数据
months = [f'{m}月' for m in range(1, 13)]
online = [120, 135, 148, 160, 155, 170, 185, 190, 175, 195, 210, 230]
offline = [80, 75, 82, 78, 85, 72, 68, 70, 75, 65, 60, 55]
total = [o + f for o, f in zip(online, offline)]

fig, axes = plt.subplots(2, 2, figsize=(14, 10))

# 1. 折线图:线上vs线下趋势
axes[0, 0].plot(months, online, 'b-o', label='线上')
axes[0, 0].plot(months, offline, 'r-s', label='线下')
axes[0, 0].set_title('线上vs线下销售趋势')
axes[0, 0].legend()
axes[0, 0].set_ylabel('销售额(万元)')

# 2. 堆叠柱状图
axes[0, 1].bar(months, online, label='线上', alpha=0.8)
axes[0, 1].bar(months, offline, bottom=online, label='线下', alpha=0.8)
axes[0, 1].set_title('月度销售构成')
axes[0, 1].legend()

# 3. 饼图:全年线上/线下占比
axes[1, 0].pie([sum(online), sum(offline)],
labels=['线上', '线下'], autopct='%1.1f%%',
colors=['#4CAF50', '#FF9800'])
axes[1, 0].set_title('全年销售渠道占比')

# 4. 散点图:线上vs线下相关性
axes[1, 1].scatter(online, offline, s=100, alpha=0.6, c='steelblue')
axes[1, 1].set_xlabel('线上销售额(万元)')
axes[1, 1].set_ylabel('线下销售额(万元)')
axes[1, 1].set_title('线上vs线下相关性')

plt.tight_layout()
plt.savefig('ecommerce_report.png', dpi=150, bbox_inches='tight')
plt.show()

图表类型选择指南

1
2
3
4
5
6
7
8
你想展示什么?
├── 趋势变化 → 折线图 (plot)
├── 对比差异 → 柱状图 (bar)
├── 占比构成 → 饼图 (pie) / 堆叠柱状图
├── 分布情况 → 直方图 (hist) / 箱线图 (boxplot)
├── 相关关系 → 散点图 (scatter)
├── 多维数据 → 气泡图 / 热力图
└── 地理数据 → 地图

图表保存最佳实践

1
2
3
4
5
6
7
8
9
10
11
12
13
# 不同场景的保存设置
# 1. 网页展示(平衡质量和大小)
plt.savefig('chart.png', dpi=150, bbox_inches='tight', optimize=True)

# 2. 印刷品质(高分辨率)
plt.savefig('chart.png', dpi=300, bbox_inches='tight')

# 3. 矢量图(可缩放不失真)
plt.savefig('chart.svg', bbox_inches='tight')
plt.savefig('chart.pdf', bbox_inches='tight')

# 4. 透明背景
plt.savefig('chart.png', transparent=True, bbox_inches='tight')

下节预告

下一课我们将学习Matplotlib进阶美化,让图表更专业。

👉 继续阅读:Matplotlib进阶-专业图表美化技巧


💬 加入学习交流群

扫码加入Python学习交流群,和数千名同学一起进步:

👉 点击加入交流群

群里不定期分享:

  • 数据分析实战案例
  • Python学习资料
  • 求职面试经验
  • 行业最新动态

推荐:AI Python数据分析实战营

🎁 限时福利:送《利用Python进行数据分析》实体书

👉 点击了解详情


课程导航

上一篇: Pandas高效数据处理技巧

下一篇: Matplotlib进阶-专业图表美化技巧


PS:Matplotlib是Python可视化的基础。虽然语法有点繁琐,但掌握后可以做任何类型的图表。



📚 推荐教材

主教材《Excel+Python 飞速搞定数据分析与处理(图灵出品)》

💬 联系我

平台账号/链接
微信扫码加好友
微博@程序员晚枫
知乎@程序员晚枫
抖音@程序员晚枫
小红书@程序员晚枫
B 站Python 自动化办公社区

主营业务:AI 编程培训、企业内训、技术咨询

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!