繪製時間序列:整合應用
在這個練習中,你要在同一個 Axes 上繪出兩組尺度不同的時間序列,並替其中一組資料加上註記。
提供的 CO2/氣溫資料是一個名為 climate_change 的 DataFrame。你也應該使用先前定義的 plot_timeseries 函式。這個函式會接收一個 Axes 物件(參數為 axes),繪製時間序列(分別由 x 與 y 參數提供),設定 x 與 y 軸標籤,並為資料顏色以及 y 軸刻度/標籤設定顏色:
plot_timeseries(axes, x, y, color, xlabel, ylabel)
接著,你會用文字標註資料中的一個重要時間點:2015-10-06,當天氣溫首次高於平均值 1 度。
本練習屬於課程
Matplotlib 資料視覺化入門
練習說明
- 使用
plot_timeseries函式將 CO2 濃度對時間作圖。將 xlabel 設為"Time (years)"、ylabel 設為"CO2 levels",color 設為'blue'。 - 建立
ax2,作為第一個 Axes 的雙生座標軸(twin)。 - 在
ax2中,將氣溫對時間作圖,將 ylabel 設為"Relative temp (Celsius)",color 設為'red'。 - 使用
ax2.annotate方法為資料加上註記。將文字">1 degree"放在 x=pd.Timestamp('2008-10-06')、y=-0.2,並以一支細灰色箭頭指向 x=pd.Timestamp('2015-10-06')、y=1。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
fig, ax = plt.subplots()
# Plot the CO2 levels time-series in blue
plot_timeseries(____, ____, ____, 'blue', ____, ____)
# Create an Axes object that shares the x-axis
ax2 = ____
# Plot the relative temperature data in red
plot_timeseries(____, ____, ____, 'red', ____, ____)
# Annotate point with relative temperature >1 degree
ax2.____(">1 degree", ____, ____, ____)
plt.show()