繪製兩個變數
如果你想繪製在相同時間點觀測到的兩個時間序列變數,可以把它們加到同一個子圖中。
如果兩個變數的尺度差異很大,你應該把它們畫在不同的 twin Axes 物件上。這些物件可以共享一個座標軸(例如時間,也就是 x 軸),而不共享另一個(y 軸)。
要建立共享 x 軸的 twin Axes 物件,可以使用 twinx 方法。
在這個練習中,你可以使用一個已載入 climate_change 資料的 DataFrame。這個 DataFrame 把 "date" 欄設為 DateTimeIndex,並包含 "co2" 欄(測量二氧化碳濃度)以及 "relative_temp" 欄(測量溫度)。
本練習屬於課程
Matplotlib 資料視覺化入門
練習說明
- 使用
plt.subplots建立 Figure 與 Axes 物件,分別命名為fig與ax。 - 使用 Axes 的
plot方法,以藍色繪製二氧化碳變數。 - 使用 Axes 的
twinx方法建立共享 x 軸的 twin Axes。 - 在 twin 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()