CHAPTER 02 · CASE STUDIES

使用 Matplotlib 绘制简单图表

本章是 Matplotlib 绘图的起点。通过最常用的三类基础图表,熟悉“准备数据 — 创建画布 — 调用绘图函数 — 显示或保存图形”这一标准流程,并理解 Figure 与 Axes 之间的关系,为后续更复杂的外观定制和布局组织打下基础。

案例数量3 组
核心内容plot() · bar() · pie()
章节编号02

CASE STUDIES

案例分区

文字说明 / 代码展示 / 图表图片 三段式结构

CASE2.1

绘制折线图

折线图适合表现数据随时间变化的趋势。示例使用 plot() 绘制上半年销售额,通过 marker 参数突出每个数据点,并补充标题与坐标轴名称,使图表具备基本的可读性。

PYTHON 示例代码
import matplotlib.pyplot as plt

# 准备数据
months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales = [120, 145, 132, 178, 205, 230]

# 创建画布并绘制折线图
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(months, sales, color='#1E3050', linewidth=2, marker='o')

# 设置标题与坐标轴名称
ax.set_title('上半年销售额趋势', fontsize=16)
ax.set_xlabel('月份')
ax.set_ylabel('销售额 / 万元')

plt.tight_layout()
plt.show()
图 2-1 · 上半年销售额趋势折线图
图 2-1 · 上半年销售额趋势折线图

提示 · 替换提示:将运行上述代码得到的图形保存为 assets/images/ch02/fig-02-01.png。

CASE2.2

绘制柱状图

柱状图用于比较不同类别之间的数值差异。示例在柱体顶端添加数值标签,让对比结果无需目测刻度即可直接读出。

PYTHON 示例代码
import matplotlib.pyplot as plt

categories = ['A 产品', 'B 产品', 'C 产品', 'D 产品']
values = [235, 182, 306, 268]

fig, ax = plt.subplots(figsize=(8, 5))
bars = ax.bar(categories, values, color='#2A3F63',
              edgecolor='#16243A', width=0.6)

# 在柱顶添加数值标签
for bar in bars:
    ax.text(bar.get_x() + bar.get_width() / 2,
            bar.get_height() + 5,
            str(int(bar.get_height())),
            ha='center', va='bottom', fontsize=10)

ax.set_ylabel('销量 / 件')
plt.tight_layout()
plt.show()
图 2-2 · 产品销量对比柱状图
图 2-2 · 产品销量对比柱状图
CASE2.3

绘制饼图

饼图用于展示各类别在总量中的占比。示例统一了配色体系,使用 autopct 自动显示百分比,并设置起始角度让区块分布更均衡。

PYTHON 示例代码
import matplotlib.pyplot as plt

labels = ['线上直营', '经销商', '电商平台', '其他渠道']
sizes = [38, 27, 24, 11]
colors = ['#16243A', '#2A3F63', '#A88450', '#D6C5A4']

fig, ax = plt.subplots(figsize=(7, 6))
ax.pie(sizes, labels=labels, colors=colors,
       autopct='%1.1f%%', startangle=90,
       wedgeprops={'edgecolor': 'white', 'linewidth': 1})

ax.set_title('销售渠道占比')
plt.tight_layout()
plt.show()
图 2-3 · 销售渠道占比饼图
图 2-3 · 销售渠道占比饼图

BACK TO INDEX

返回作品集首页

浏览其他章节内容

返回首页 →