CASEEX.1
电商销售数据看板
使用 GridSpec 将画布划分为上下两部分:上方展示实际与目标折线对比,下方分别展示月度差额和总量占比,形成一页式看板。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales = np.array([120, 145, 132, 178, 205, 230])
target = np.array([130, 140, 150, 165, 190, 220])
fig = plt.figure(figsize=(12, 7))
gs = GridSpec(2, 2, figure=fig, hspace=0.35, wspace=0.25)
ax1 = fig.add_subplot(gs[0, :])
ax1.plot(months, sales, marker='o', color='#16243A', label='实际销售额')
ax1.plot(months, target, linestyle='--', color='#A88450', label='目标销售额')
ax1.legend(frameon=False)
ax1.set_title('上半年销售目标完成情况')
ax2 = fig.add_subplot(gs[1, 0])
ax2.bar(months, sales - target, color='#2A3F63')
ax2.set_title('月度差额')
ax3 = fig.add_subplot(gs[1, 1])
ax3.pie([sales.sum(), target.sum()], labels=['实际', '目标'],
autopct='%1.1f%%', colors=['#16243A', '#D6C5A4'])
ax3.set_title('总量对比')
fig.suptitle('电商销售数据看板', fontsize=17, y=0.98)
plt.show()
知识点
- GridSpec 让“总—分”结构在一页内完成,主图在上、细节在下。
- 折线对比目标与实际,柱状展示差额,饼图展示总量占比,三种图形各司其职。
- suptitle() 给整块看板一个统一标题,强化整体感。
学习心得
综合案例让我学会先规划信息层级,再决定画什么图。把前面各章的技术串起来后,作品集才从练习题变成能讲清楚一个业务问题的报告。