绘制折线图
折线图适合表现数据随时间变化的趋势。示例使用 plot() 绘制上半年销售额,通过 marker 参数突出每个数据点,并补充标题与坐标轴名称,使图表具备基本的可读性。
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()
知识点
- Figure 是画布,Axes 是绘图区域;plt.subplots() 同时返回两者,是推荐的面向对象写法。
- plot() 的前两个参数依次为横轴与纵轴数据,marker 用于强调离散的数据点。
- set_title()、set_xlabel()、set_ylabel() 分别补充标题和坐标轴含义,tight_layout() 防止标签被裁切。
学习心得
第一次把销售数据画成折线时才发现,同样的数据换成曲线后,趋势比表格直观得多。面向对象写法虽然比 plt.plot() 多写一行,但后续要调整某张图时定位更清楚,适合在课程作业里逐步扩展。
提示 · 替换提示:将运行上述代码得到的图形保存为 assets/images/ch02/fig-02-01.png。