Python Data Visualization

10 个 Matplotlib 绘图练习

从柱形图到雷达图,覆盖十种基础图表类型。所有图表均由练习代码真实运行生成,数据可复现。

10练习图表
10图表类型
10完整源码

全部练习 · 共 10 个

01

单组柱形图电商平台各品类月销售额

bar()

统计电商平台 5 个品类的月销售额,用柱形图直观比较各品类销售规模,食品生鲜与电子产品领先。

电商平台各品类月销售额柱形图
查看源代码
categories = ['电子产品', '服装鞋帽', '家居百货', '美妆个护', '食品生鲜']
sales = [550, 420, 280, 390, 610]  # 万元

plt.figure(figsize=(8, 5))
plt.bar(categories, sales, color='steelblue')
plt.title('电商平台各品类月销售额')
plt.xlabel('品类'); plt.ylabel('销售额(万元)')
plt.tight_layout(); plt.show()
02

多组条形图四城市两季度人均消费支出

barh()

对比北京、上海、广州、深圳四个城市在两个季度的人均消费支出,横向条形图便于多组数据并排比较。

四城市两季度人均消费支出条形图
查看源代码
cities = ['北京', '上海', '广州', '深圳']
q1_spend = [12000, 11500, 9800, 10500]
q2_spend = [13500, 12800, 10900, 11900]
y = np.arange(len(cities)); height = 0.35

plt.figure(figsize=(9, 5))
plt.barh(y - height/2, q1_spend, height, label='Q1 支出')
plt.barh(y + height/2, q2_spend, height, label='Q2 支出')
plt.yticks(y, cities); plt.legend()
plt.xlabel('人均消费支出(元)'); plt.ylabel('城市')
plt.tight_layout(); plt.show()
03

箱形图不同工艺下零件质量分布

boxplot()

比较三种工艺生产零件的质量分布。工艺 B 最稳定,工艺 C 波动最大并出现 60、130 两个异常值。

不同工艺零件质量分布箱形图
查看源代码
data_a = np.random.normal(100, 5, 50)
data_b = np.random.normal(105, 3, 50)
data_c = np.append(np.random.normal(95, 8, 48), [130, 60])

plt.figure(figsize=(8, 5))
plt.boxplot([data_a, data_b, data_c],
            tick_labels=['工艺A', '工艺B', '工艺C'],
            showmeans=True)
plt.title('不同工艺下零件质量分布')
plt.xlabel('工艺'); plt.ylabel('质量(克)')
plt.tight_layout(); plt.show()
04

折线图营收与利润年度变化

plot()

在同一坐标系内展示某公司 2019—2025 年营收与利润的年度趋势,两项指标均保持稳定增长。

公司营收与利润年度折线图
查看源代码
years   = [2019, 2020, 2021, 2022, 2023, 2024, 2025]
revenue = [2.5, 3.1, 4.0, 5.2, 6.5, 7.8, 8.5]  # 亿元
profit  = [0.5, 0.7, 0.9, 1.3, 1.8, 2.2, 2.5]

plt.plot(years, revenue, marker='o', label='营收')
plt.plot(years, profit,  marker='s', label='利润')
plt.xticks(years); plt.legend(); plt.grid(alpha=0.3)
plt.title('公司营收与利润年度变化趋势')
plt.xlabel('年份'); plt.ylabel('金额(亿元)')
plt.show()
05

直方图班级数学成绩频率分布

hist()

将 50 名学生的数学成绩按 10 个区间统计频数,成绩主要集中在中段,整体近似正态分布。

班级数学成绩频率分布直方图
查看源代码
scores = np.random.normal(75, 15, 50)
scores = np.clip(scores, 40, 100)   # 限制范围 [40, 100]

plt.figure(figsize=(8, 5))
plt.hist(scores, bins=10, range=(40, 100),
         color='teal', edgecolor='white')
plt.title('班级数学成绩频率分布')
plt.xlabel('分数'); plt.ylabel('频数')
plt.tight_layout(); plt.show()
06

饼图项目团队成员专业构成

pie()

展示 40 人项目团队的专业构成比例,后端开发占比最高(37.5%),UI/UX 设计最少。

项目团队成员专业构成饼图
查看源代码
roles  = ['后端开发', '前端开发', 'UI/UX设计', '软件测试']
counts = [15, 12, 5, 8]

plt.figure(figsize=(7, 7))
plt.pie(counts, labels=roles, autopct='%.1f%%',
        startangle=90, counterclock=False)
plt.title('项目团队成员专业构成')
plt.tight_layout(); plt.show()
07

气泡图人口、GDP 与人均收入关系

scatter()

以人口为 X 轴、GDP 为 Y 轴、人均收入映射气泡大小与颜色,一次呈现三个变量之间的关系。

城市人口GDP与人均收入气泡图
查看源代码
population = [300, 1500, 800, 500, 1200, 900]  # 万人
gdp        = [150, 700, 350, 200, 600, 450]    # 亿元
income     = [6.5, 9.2, 7.8, 6.0, 8.5, 7.0]    # 万元
sizes = [v * 150 for v in income]

sc = plt.scatter(population, gdp, s=sizes, c=income,
                 cmap='viridis', alpha=0.7, edgecolors='k')
for x, yv, name in zip(population, gdp, cities):
    plt.annotate(name, (x, yv), xytext=(8, 5),
                 textcoords='offset points')
plt.colorbar(sc, label='人均收入(万元)')
plt.show()
08

堆积面积图APP 活跃用户来源变化

stackplot()

按月份展示 APP 活跃用户三类来源(自然流量、广告投放、内容营销)的累积变化,总量与结构一目了然。

APP活跃用户来源堆积面积图
查看源代码
months = [1, 2, 3, 4, 5, 6]
organic_traffic = [10, 12, 15, 18, 20, 22]  # 万人
ads_traffic     = [5, 8, 10, 9, 11, 13]
content_traffic = [3, 4, 6, 8, 10, 12]

plt.stackplot(months, organic_traffic, ads_traffic, content_traffic,
              labels=['自然流量', '广告投放', '内容营销'],
              colors=['#4C72B0', '#DD8452', '#55A868'], alpha=0.85)
plt.xticks(months); plt.legend(loc='upper left')
plt.xlabel('月份'); plt.ylabel('活跃用户(万人)')
plt.show()
09

误差棒图处理时间对反应强度的影响

errorbar()

展示不同处理时间下平均反应强度及其测量标准差,随时间延长强度上升,同时不确定性也随之增大。

处理时间对反应强度影响的误差棒图
查看源代码
time = [1, 2, 4, 8, 12]                # 小时
mean_intensity = [15, 22, 35, 48, 55]
std_dev = [1.5, 2.0, 3.5, 4.0, 5.5]

plt.errorbar(time, mean_intensity, yerr=std_dev,
             fmt='o-', capsize=5, color='darkred',
             ecolor='gray', elinewidth=1.5,
             label='平均反应强度 ± 标准差')
plt.xticks(time); plt.legend(); plt.grid(alpha=0.3)
plt.xlabel('处理时间(小时)'); plt.ylabel('平均反应强度')
plt.show()
10

雷达图两款产品性能指标对比

polar()

在极坐标系中对比产品 A 与产品 B 在性能、设计、续航、价格、服务五个维度的得分,各有优势。

两款产品性能指标雷达图
查看源代码
labels = ['性能', '设计', '续航', '价格', '服务']
product_a = [9.0, 7.5, 8.0, 6.5, 7.0]
product_b = [7.0, 8.5, 7.5, 8.0, 9.0]

angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False).tolist()
a_vals = product_a + product_a[:1]
b_vals = product_b + product_b[:1]
angles_closed = angles + angles[:1]

ax = plt.subplot(111, polar=True)
ax.plot(angles_closed, a_vals, 'o-', lw=2, label='产品A')
ax.fill(angles_closed, a_vals, alpha=0.2)
ax.plot(angles_closed, b_vals, 's-', lw=2, label='产品B')
ax.fill(angles_closed, b_vals, alpha=0.2)
ax.set_xticks(angles); ax.set_xticklabels(labels)
ax.set_ylim(0, 10); ax.legend()
plt.show()