图形与坐标轴
本课属于 Coddy Machine Learning 学习旅程的“数据与图表”单元。第 24 课,共 60 课。
实际代码会为绘制的图表命名。plt.subplots() 会返回两个对象:figure,也就是整张图;以及 axes,也就是其中的图表:
fig, ax = 会同时捕获这两者。然后所有操作都在 ax 上进行:
years = [2021, 2022, 2023, 2024]
members = [35, 48, 61, 59]
fig, ax = plt.subplots()
ax.plot(years, members)
ax.set_title("Club Members")
ax.set_xlabel("Year")
ax.set_ylabel("Members")
plt.show()绘图方法的名称保持不变:ax.plot、ax.scatter、ax.legend。文本方法则加上 set_。
为什么要这么做?很快,一个图形中就会有多个图表,而 ax 用来表示你指的是哪一个。从现在起,每个图表都以这种方式开始。
挑战
中等初始代码使用 plt 函数绘制了图书馆的 7 个分馆,每个分馆对应一个点。请用 ax 的形式重写:
- 从
fig, ax = plt.subplots()开始。 - 使用
ax方法绘制点、标题和两个标签,文本保持相同。 - 删除旧的
plt代码行,但保留plt.show()。
图表保持不变,只改变代码。初始代码的报告显示 Drawn with fig and ax: no。你的报告应显示:
Charts drawn: 1
Drawn with fig and ax: yes
Title: Library Branches
X label: Hours open per week
Y label: Loans per week
Lines: 0
Dots: 7
Across (x): [30, 45, 38, 52, 24, 60, 41]
Up (y): [410, 690, 520, 800, 300, 930, 610]亲手试试
import matplotlib.pyplot as plt
# 市图书馆的每个分馆对应一个值
hours = [30, 45, 38, 52, 24, 60, 41]
loans = [410, 690, 520, 800, 300, 930, 610]
# 用 fig, ax = plt.subplots() 和 ax 的方法重写这张图
plt.scatter(hours, loans)
plt.title("Library Branches")
plt.xlabel("Hours open per week")
plt.ylabel("Loans per week")
plt.show()
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
数据与图表中的所有课
自己练习: Python 在线编译器