author: 专注Python实战,分享爬虫与数据分析干货
title: Python爬虫实战㉒|Matplotlib基础,画出专业级数据图表
update: 2026-04-26
tags: Python,Matplotlib,可视化,折线图,柱状图,散点图,饼图,图表

作者:专注Python实战,分享爬虫与数据分析干货
更新时间:2026年4月
适合人群:有Pandas基础、想让数据"说话"的开发者


前言:一图胜千言

10万条数据堆在表格里,老板看不懂。画成图表,5秒理解。

Matplotlib = Python可视化的基石。 所有高级图表库(Seaborn、Pyecharts)都基于它。


一、基础配置

1.1 安装与中文字体

pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
import matplotlib.pyplot as plt
import matplotlib

# 中文字体配置(Windows)
matplotlib.rcParams["font.sans-serif"] = ["SimHei"]      # 黑体
matplotlib.rcParams["axes.unicode_minus"] = False          # 负号正常显示

# 或者用微软雅黑
matplotlib.rcParams["font.sans-serif"] = ["Microsoft YaHei"]

1.2 第一个图表

import matplotlib.pyplot as plt

# 数据
x = [1, 2, 3, 4, 5]
y = [10, 25, 18, 30, 22]

# 画图
plt.figure(figsize=(8, 5))     # 图表大小
plt.plot(x, y)                 # 折线图
plt.title("销售趋势")          # 标题
plt.xlabel("月份")             # X轴标签
plt.ylabel("销量")             # Y轴标签
plt.grid(True, alpha=0.3)     # 网格线
plt.savefig("sales_trend.png", dpi=150, bbox_inches="tight")  # 保存
plt.show()

二、常用图表类型

2.1 折线图(趋势)

import matplotlib.pyplot as plt
import numpy as np

months = [f"{i}月" for i in range(1, 13)]
sales_A = [100, 120, 115, 130, 140, 155, 160, 170, 165, 180, 190, 210]
sales_B = [80, 95, 90, 100, 110, 120, 125, 135, 130, 145, 150, 165]

plt.figure(figsize=(10, 6))
plt.plot(months, sales_A, "o-", label="产品A", color="#4472C4", linewidth=2, markersize=6)
plt.plot(months, sales_B, "s--", label="产品B", color="#ED7D31", linewidth=2, markersize=6)

plt.title("月度销售趋势对比", fontsize=16, fontweight="bold")
plt.xlabel("月份", fontsize=12)
plt.ylabel("销量", fontsize=12)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("line_chart.png", dpi=150)
plt.show()

2.2 柱状图(对比)

categories = ["手机", "电脑", "耳机", "键盘", "显示器"]
sales = [450, 320, 580, 290, 210]
colors = ["#4472C4", "#ED7D31", "#A5A5A5", "#FFC000", "#5B9BD5"]

plt.figure(figsize=(8, 5))
bars = plt.bar(categories, sales, color=colors, width=0.6, edgecolor="white")

# 添加数值标签
for bar, val in zip(bars, sales):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 10,
             str(val), ha="center", va="bottom", fontsize=12, fontweight="bold")

plt.title("各品类销量对比", fontsize=16, fontweight="bold")
plt.ylabel("销量", fontsize=12)
plt.ylim(0, max(sales) * 1.15)
plt.tight_layout()
plt.savefig("bar_chart.png", dpi=150)
plt.show()

2.3 水平柱状图(排名)

products = [f"产品{i}" for i in range(1, 11)]
values = sorted(np.random.randint(100, 500, 10))
colors = plt.cm.RdYlGn(np.linspace(0.2, 0.8, len(products)))

plt.figure(figsize=(8, 6))
plt.barh(products, values, color=colors, height=0.6)
plt.title("产品销量排名", fontsize=16, fontweight="bold")
plt.xlabel("销量", fontsize=12)
plt.tight_layout()
plt.savefig("barh_chart.png", dpi=150)
plt.show()

2.4 散点图(相关性)

np.random.seed(42)
price = np.random.uniform(100, 5000, 100)
sales = 1000 - price * 0.15 + np.random.normal(0, 50, 100)

plt.figure(figsize=(8, 6))
plt.scatter(price, sales, alpha=0.6, c="#4472C4", s=50, edgecolors="white")

# 添加趋势线
z = np.polyfit(price, sales, 1)
p = np.poly1d(z)
plt.plot(price, p(price), "r--", linewidth=2, label=f"趋势线: y={z[0]:.2f}x+{z[1]:.0f}")

plt.title("价格与销量关系", fontsize=16, fontweight="bold")
plt.xlabel("价格", fontsize=12)
plt.ylabel("销量", fontsize=12)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("scatter_chart.png", dpi=150)
plt.show()

2.5 饼图(占比)

labels = ["手机", "电脑", "耳机", "其他"]
sizes = [35, 25, 20, 20]
colors = ["#4472C4", "#ED7D31", "#A5A5A5", "#FFC000"]
explode = (0.05, 0, 0, 0)  # 突出显示第一个

plt.figure(figsize=(8, 8))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct="%1.1f%%", startangle=90, textprops={"fontsize": 14})
plt.title("品类销售占比", fontsize=16, fontweight="bold")
plt.tight_layout()
plt.savefig("pie_chart.png", dpi=150)
plt.show()

2.6 直方图(分布)

np.random.seed(42)
prices = np.random.lognormal(mean=7.5, sigma=0.5, size=1000)

plt.figure(figsize=(8, 5))
plt.hist(prices, bins=30, color="#4472C4", edgecolor="white", alpha=0.8)
plt.axvline(np.mean(prices), color="red", linestyle="--", label=f"均值: {np.mean(prices):.0f}")
plt.axvline(np.median(prices), color="green", linestyle="--", label=f"中位数: {np.median(prices):.0f}")
plt.title("商品价格分布", fontsize=16, fontweight="bold")
plt.xlabel("价格", fontsize=12)
plt.ylabel("数量", fontsize=12)
plt.legend(fontsize=12)
plt.tight_layout()
plt.savefig("hist_chart.png", dpi=150)
plt.show()

三、子图(subplot)

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

# 子图1:折线图
axes[0, 0].plot(months, sales_A, "o-", color="#4472C4")
axes[0, 0].set_title("月度趋势")

# 子图2:柱状图
axes[0, 1].bar(categories, sales, color=colors)
axes[0, 1].set_title("品类对比")

# 子图3:散点图
axes[1, 0].scatter(price, sales, alpha=0.5, c="#4472C4")
axes[1, 0].set_title("价格-销量关系")

# 子图4:饼图
axes[1, 1].pie(sizes, labels=labels, colors=colors, autopct="%1.1f%%")
axes[1, 1].set_title("品类占比")

fig.suptitle("数据分析仪表板", fontsize=18, fontweight="bold")
plt.tight_layout()
plt.savefig("dashboard.png", dpi=150)
plt.show()

四、知识卡

图表类型 函数 适用场景
折线图 plt.plot() 趋势变化
柱状图 plt.bar() 类别对比
水平柱状图 plt.barh() 排名
散点图 plt.scatter() 相关性
饼图 plt.pie() 占比
直方图 plt.hist() 分布
子图 plt.subplots() 多图组合

五、课后作业

必做题:

  1. 画出折线图展示月度趋势
  2. 画柱状图对比不同类别
  3. 画散点图分析两个变量的关系

选做题:

  1. 用subplot制作4合1仪表板
  2. 保存高清图片用于报告

有问题欢迎评论区留言,大家一起讨论!


标签:Python | Matplotlib | 可视化 | 折线图 | 柱状图 | 散点图 | 饼图

更多推荐