绘制两个变量
如果您想在同一个时间点绘制两个时间序列变量,可以把它们添加到同一个子图中。
如果两个变量的数值范围差异很大,建议在不同的双轴 Axes 对象中绘制。这样的对象可以共享一条坐标轴(例如时间,即 x 轴),而不共享另一条(y 轴)。
要创建一个共享 x 轴的双轴 Axes 对象,请使用 twinx 方法。
在本练习中,您将使用一个已加载 climate_change 数据的 DataFrame。该 DataFrame 已将 "date" 列设置为 DateTimeIndex,并包含名为 "co2" 的二氧化碳测量值列和名为 "relative_temp" 的温度测量值列。
本练习是课程的一部分
Matplotlib 数据可视化入门
练习说明
- 使用
plt.subplots创建 Figure 和 Axes 对象,分别命名为fig和ax。 - 使用 Axes 的
plot方法以蓝色绘制二氧化碳变量。 - 使用 Axes 的
twinx方法创建一个共享 x 轴的双轴 Axes。 - 在双轴 Axes 上使用其
plot方法以红色绘制相对温度变量。
交互式实操练习
通过完成这段示例代码来试试这个练习。
import matplotlib.pyplot as plt
# Initalize a Figure and Axes
____
# Plot the CO2 variable in blue
ax.plot(____, ____, color=____)
# Create a twin Axes that shares the x-axis
ax2 = ____
# Plot the relative temperature in red
____.plot(____, ____, color=____)
plt.show()