开始使用免费开始使用

使用绘图函数

定义函数可以让我们复用相同的代码,而不用反复粘贴。程序员有时把这称为 "Don't repeat yourself"

在上一个练习中,您定义了一个名为 plot_timeseries 的函数:

plot_timeseries(axes, x, y, color, xlabel, ylabel)

它接收一个 Axes 对象(参数名为 axes)、时间序列数据(参数 xy)、颜色名称(字符串,作为 color 参数),以及 x 轴和 y 轴标签(参数 xlabelylabel)。在本练习中,函数 plot_timeseries 已经为您定义并提供。

请使用该函数绘制 climate_change 时间序列数据。它是一个 pandas DataFrame 对象,索引为测量日期的 DateTimeIndex,包含 co2relative_temp 两列。

本练习是课程的一部分

Matplotlib 数据可视化入门

查看课程

练习说明

  • 在提供的 ax 对象上,使用函数 plot_timeseries"co2" 列绘制为蓝色,x 轴标签为 "Time (years)",y 轴标签为 "CO2 levels"
  • 使用 ax.twinx 方法为图形添加一个与 ax 共享 x 轴的 Axes 对象。
  • 使用函数 plot_timeseries"relative_temp" 列的数据以红色绘制到新的双轴 Axes 对象上,x 轴标签为 "Time (years)",y 轴标签为 "Relative temperature (Celsius)"

交互式实操练习

通过完成这段示例代码来试试这个练习。

fig, ax = plt.subplots()

# Plot the CO2 levels time-series in blue
____(____, ____, ____, "blue", ____, ____)

# Create a twin Axes object that shares the x-axis
ax2 = ____

# Plot the relative temperature data in red
____(____, ____, ____, "red", ____, ____)

plt.show()
编辑并运行代码