使用繪圖函式
定義函式可以重複使用相同的程式碼,而不必把整段再寫一次。程式設計師有時會說「Don't repeat yourself」(不要重複自己)。
在上一個練習中,你定義了一個名為 plot_timeseries 的函式:
plot_timeseries(axes, x, y, color, xlabel, ylabel)
它會接收一個 Axes 物件(引數為 axes)、時間序列資料(x 與 y 引數)、顏色名稱(字串,提供給 color 引數),以及 x 軸與 y 軸標籤(xlabel 與 ylabel 引數)。在本練習中,plot_timeseries 函式已經替你定義並提供好了。
請使用這個函式來繪製 climate_change 的時間序列資料。這是一個 pandas DataFrame 物件,具有測量日期的 DateTimeIndex,並包含 co2 與 relative_temp 欄位。
本練習屬於課程
Matplotlib 資料視覺化入門
練習說明
- 在提供的
ax物件中,使用plot_timeseries函式以藍色繪出"co2"欄位,x 軸標籤為"Time (years)",y 軸標籤為"CO2 levels"。 - 使用
ax.twinx方法在圖形中新增與ax共享 x 軸的 Axes 物件。 - 使用
plot_timeseries函式,將"relative_temp"欄位的資料以紅色加入 twin 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()