1. 程式人生 > 其它 >matplotlib構圖 案例1 氣溫

matplotlib構圖 案例1 氣溫

matplotlib構圖 案例1 氣溫

import csv
import matplotlib.pyplot as plt
from datetime import datetime

# 設定字型
# plt.rcParams['font.sans-serif'] = ['SimHei']  # 漢字字型,優先使用楷體,如果找不到楷體,則使用黑體
# plt.rcParams['font.size'] = 12  # 字型大小
# plt.rcParams['axes.unicode_minus'] = False  # 正常顯示負號

# file = 'data/sitka_weather_07-2018_simple.csv'
file = 'data/sitka_weather_2018_simple.csv' with open(file) as f: reader = csv.reader(f) header_row = next(reader) # 滾動到下一行 # print(header_row) # 在迴圈中,對列表呼叫了enumerate()來獲取每個元素的索引及其值。 for index, column_header in enumerate(header_row): print(index, column_header) # 從檔案中獲取最高溫度。
# 建立一個名為highs的空列表,再遍歷檔案中餘下的各行)。 # 閱讀器物件從其停留的地方繼續往下讀取CSV檔案,每次都自動返回當前所處位置的下一行。 # 由於已經讀取了檔案頭行,這個迴圈將從第二行開始——從這行開始包含的是實際資料。每次執行迴圈時,都將索引5處(TMAX列)的資料附加到highs末尾。 # 在檔案中,這項資料是以字串格式儲存的,因此在附加到highs末尾前,使用函式int()將其轉換為數值格式,以便使用。 dates, highs,lows = [], [],[] # 一個日期陣列x軸,一個溫度值陣列y軸 for row in
reader: current_date = datetime.strptime(row[2], '%Y-%m-%d') # 格式化日期事件 high = int(row[5]) low = int(row[6]) dates.append(current_date) highs.append(high) lows.append(low) print(dates) print(highs) print(lows) # 根據最高溫度繪製圖形。 # 圖形的型別 plt.style.use('seaborn') # plt.subplots()是一個返回包含圖形和軸物件的元組的函式.因此,在使用時fig, ax = plt.subplots(), # 將此元組解壓縮到變數fig和ax.有fig,如果你想改變人物級別的屬性或儲存數字作為以後的影象檔案是非常有用的 fig, ax = plt.subplots() # 將最高溫度列表傳給plot(),並傳遞c='red'以便將資料點繪製為紅色。 # 實參alpha指定顏色的透明度。alpha值為0表示完全透明,為1(預設設定)表示完全不透明。 # 通過將alpha設定為0.5,可讓紅色和藍色折線的顏色看起來更淺。 ax.plot(dates, highs, c='red',alpha=0.5) # 最 高 溫度 ax.plot(dates, lows, c='blue',alpha=0.5) # 最 低 溫度 ax.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1) # 設定圖形的格式。 ax.set_title("2018All Years TMAX", fontsize=24) ax.set_xlabel('', fontsize=16) fig.autofmt_xdate() # 呼叫fig.autofmt_xdate()來繪製傾斜的日期標籤,以免其彼此重疊。 ax.set_ylabel("wendu(F)", fontsize=16) # axis : 可選{‘x’, ‘y’, ‘both’} ,選擇對哪個軸操作,預設是’both’ # which : 可選{‘major’, ‘minor’, ‘both’} 選擇對主or副座標軸進行操作 # labelsize : float/str, 刻度值字型大小 ax.tick_params(axis='both', which='major', labelsize=16) plt.show()