範例專題 - 使用CSV檔案製作氣象圖表 : exProject-CsvWeather.py

範例專題 - 使用CSV檔案製作氣象圖表 : exProject-CsvWeather.py 

大綱

讀取台北市氣象資料,列出標題

讀取台北市 2020年 一月份氣象資料 weatherDataTaipei-2020-01.csv 。使用 VSCode 閱讀,如下:

範例 exProject-CsvWeather-01.py : 讀取台北市 2020年 一月份氣象資料檔案 weatherDataTaipei-2020-01.csv 然後列出標題列 。第7行,我們使用Python 內建函式 next() 獲取下一個元素(下一行)。

# exProject-CsvWeather-01.py
import csv

fileName = 'WeatherDataTaipei-2020-01.csv'
with open(fileName, encoding='utf-8') as csvFile:
    csvReaderObj = csv.reader(csvFile)
    headerRow = next(csvReaderObj)         # 讀取文件下一行,
print(headerRow)

執行結果

['日期', '最高溫度', '平均溫度', '最低溫度']

範例 exProject-CsvWeather-02.py : 讀取台北市 2020年 一月份氣象資料檔案 weatherDataTaipei-2020-01.csv 然後列出標題列 。第7行,我們使用Python 內建函式 next() 獲取下一個元素(下一行)。使用 enumerate() 列出標題列的各個欄位索引值與資料。

# exProject-CsvWeather-02.py
import csv

fileName = 'WeatherDataTaipei-2020-01.csv'
with open(fileName, encoding='utf-8') as csvFile:
    csvReaderObj = csv.reader(csvFile)
    headerRow = next(csvReaderObj)         # 讀取文件下一行
for i, header in enumerate(headerRow):
    print(i, header)

執行結果

0  日期
1  最高溫度
2  平均溫度
3  最低溫度

讀取最高溫度、最低溫度

範例 exProject-CsvWeather-03.py : 讀取台北市 2020年 一月份氣象資料檔案 weatherDataTaipei-2020-01.csv ,然後將最高溫度存放在串列 highTemps 中,將最低溫度存放在串列 lowTemps 中。

# exProject-CsvWeather-03.py
import csv

fileName = 'WeatherDataTaipei-2020-01.csv'
with open(fileName, encoding='utf-8') as csvFile:
    csvReaderObj = csv.reader(csvFile)
    headerRow = next(csvReaderObj)         # 讀取文件下一行
    highTemps, lowTemps = [], []        # 設定空串列
    for row in csvReaderObj:
        highTemps.append(row[1])        # 儲存最高溫度
        lowTemps.append(row[3])         # 儲存最低溫度

print("最高溫度 : ", highTemps)
print("最低溫度 : ", lowTemps)  

執行結果

最高溫度 : ['26', '25', '22', '27', '25', '25', '26', '22', '18', '20', '21', '22', '18', '15', '15', '16', '23', '23', '22', '18', '15', '17', '16', '17', '18', '19', '24', '26', '25', '27', '18']
最低溫度 : ['20', '18', '19', '20', '19', '20', '20', '18', '16', '16', '18', '18', '14', '12', '13', '13', '16', '18', '18', '12', '12', '12', '13', '14', '13', '13', '13', '16', '17', '14', '14']

繪製最高溫

Matplotlib 是一個綜合性的第三方套件,用於在 Python 中創建靜態、動畫和交互式可視化物件。安裝指令為 :  pip install matplotlib 

範例 exProject-CsvWeather-04.py : 繪製台北市2020年一月份,每天最高溫度。

# exProject-CsvWeather-04.py
import csv
import matplotlib.pyplot as plt

fileName = 'WeatherDataTaipei-2020-01.csv'
with open(fileName, encoding='utf-8') as csvFile:
    csvReaderObj = csv.reader(csvFile)
    headerRow = next(csvReaderObj)         # 讀取文件下一行
    highTemps = []                       # 設定空串列
    for row in csvReaderObj:
        highTemps.append(int(row[1]))    # 儲存最高溫

plt.plot(highTemps)
plt.title("Taipei High Temperature in Jan. 2020", fontsize=24)
plt.xlabel("", fontsize=14)
plt.ylabel("Temperature (C)", fontsize=14)
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

執行結果

設定繪圖區大小

在以上程式新增一行,如下: 

plt.figure(dpi=80, figsize=(12, 8)) # 設定繪圖區大小

此方法 plt.figure() 設定以 單位dpi=80, 寬度為 80dpi*12=960dpi, 高度為 80dpi*8=640pdi。

範例 exProject-CsvWeather-04.py : 繪製台北市2020年一月份,每天最高溫度。

# exProject-CsvWeather-05.py
import csv
import matplotlib.pyplot as plt

fileName = 'WeatherDataTaipei-2020-01.csv'
with open(fileName, encoding='utf-8') as csvFile:
    csvReaderObj = csv.reader(csvFile)
    headerRow = next(csvReaderObj)         # 讀取文件下一行
    highTemps = []                       # 設定空串列
    for row in csvReaderObj:
        highTemps.append(int(row[1]))    # 儲存最高溫
        
plt.figure(dpi=80, figsize=(12, 8))         # 設定繪圖區大小   
plt.plot(highTemps)
plt.title("Taipei High Temperature in Jan. 2020", fontsize=24)
plt.xlabel("", fontsize=14)
plt.ylabel("Temperature (C)", fontsize=14)
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

日期格式

在天氣圖表中,我們需要在X軸刻度上加上日期,這時我們需要導入 Python 內建的 datetime模組 ,使用以下指令導入:

from datetime import datetime

然後使用以下方法將日期字串解析為日期物件:

strptime(string, format)

format格式的代碼入下.....更多請參考這裡

  • %y 兩位數的年份表示(00-99)
  • %Y 四位數的年份表示(000-9999)
  • %m 月份(01-12)
  • %d 月內中的一天(0-31)
  • %H 24小時制小時數(0-23)
  • %I 12小時制小時數(01-12)
  • %M 分鐘數(00-59)
  • %S 秒(00-59)
  • %a 本地簡化星期名稱
  • %A 本地完整星期名稱
  • %b 本地簡化的月份名稱
  • %B 本地完整的月份名稱
  • %c 本地相應的日期表示和時間表示
  • %j 年內的一天(001-366)
  • %p 本地A.M.或P.M.的等價符
  • %U 一年中的星期數(00-53)星期天為星期的開始
  • %w 星期(0-6),星期天為 0,星期一為 1,以此類推。
  • %W 一年中的星期數(00-53)星期一為星期的開始
  • %x 本地相應的日期表示
  • %X 本地相應的時間表示
  • %Z 當前時區的名稱

範例 exProject-CsvWeather-06.py : 將字串轉為日期物件。

# exProject-CsvWeather-06.py
from datetime import datetime

dateObj = datetime.strptime('2020/1/1', '%Y/%m/%d')
print(dateObj)

執行結果

2020-01-01 00:00:00

圖表增加日期刻度、日期位置旋轉

我們使用第三方模組 matplotlib 的 plot() 方法 ,plt.plot(dates, highTemps)  # 圖標增加日期刻度,和 autofmt_xdate() 方法,  fig.autofmt_xdate() # 日期旋轉 ,其預設的角度為45度,我們可以在旋轉日期的參數中加入角度,更改為60度 ,例如 : fig.autofmt_xdate(rotation=60)。

範例 exProject-CsvWeather-07.py : 使用 plot() 方法,在圖表增加日期刻度。

# exProject-CsvWeather-07.py
import csv
import matplotlib.pyplot as plt
from datetime import datetime

fileName = 'WeatherDataTaipei-2020-01.csv'
with open(fileName, encoding='utf-8') as csvFile:
    csvReaderObj = csv.reader(csvFile)
    headerRow = next(csvReaderObj)          # 讀取文件下一行
    dates, highTemps = [], []               # 設定空串列
    for row in csvReaderObj:
        highTemps.append(int(row[1]))       # 儲存最高溫
        currentDate = datetime.strptime(row[0], "%Y/%m/%d")
        dates.append(currentDate)
       
fig = plt.figure(dpi=80, figsize=(12, 8))   # 設定繪圖區大小                  
plt.plot(dates, highTemps)                  # 圖標增加日期刻度
fig.autofmt_xdate()                         # 日期旋轉
plt.title("Taipei High Temperature in Jan. 2020", fontsize=24)
plt.xlabel("", fontsize=14)
plt.ylabel("Temperature (C)", fontsize=14)
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

執行結果

繪製最高最低溫

範例 exProject-CsvWeather-08.py : 利用檔案中的最高溫度與最低溫度的兩個欄位,繪製溫度圖表。本程式有兩個重點,重點1 : 第11-21行,我們使用了異常處理方式 try: .....except Exception: ......else:... ,這是在真實的網路世界中,常常會有: 資料少了或隔式錯誤...等,往往會造成程式中斷,所以使用異常處理方式。 重點2 :  第24-25行,分別繪製了最高溫與最低溫兩條線圖。

# exProject-CsvWeather-08.py
import csv
import matplotlib.pyplot as plt
from datetime import datetime

fileName = 'WeatherDataTaipei-2020-01.csv'
with open(fileName, encoding='utf-8') as csvFile:
    csvReaderObj = csv.reader(csvFile)
    headerRow = next(csvReaderObj)          # 讀取文件下一行
    dates, highTemps, lowTemps = [], [], [] # 設定空串列
    for row in csvReaderObj:
        try:                    
            currentDate = datetime.strptime(row[0], "%Y/%m/%d")
            highTemp = int(row[1])          # 設定最高溫
            lowTemp = int(row[3])           # 設定最低溫
        except Exception:
            print('有缺值')
        else:
            highTemps.append(highTemp)      # 儲存最高溫
            lowTemps.append(lowTemp)        # 儲存最低溫
            dates.append(currentDate)       # 儲存日期
       
fig = plt.figure(dpi=80, figsize=(12, 8))   # 設定繪圖區大小
plt.plot(dates, highTemps)                  # 繪製最高溫
plt.plot(dates, lowTemps)                   # 繪製最低溫
fig.autofmt_xdate()                         # 日期旋轉
plt.title("Weather Report, Jan. 2017", fontsize=24)
plt.xlabel("", fontsize=14)
plt.ylabel("Temperature (C)", fontsize=14)
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

執行結果

範例 exProject-CsvWeather-09.py : 延續範例 exProject-CsvWeather-08.py,我們新增一行程式碼,第26行  plt.fill_between(dates, highTemps, lowTemps, color='y', alpha=0.2) # 填滿區間 。 

# exProject-CsvWeather-09.py
import csv
import matplotlib.pyplot as plt
from datetime import datetime

fileName = 'WeatherDataTaipei-2020-01.csv'
with open(fileName, encoding='utf-8') as csvFile:
    csvReaderObj = csv.reader(csvFile)
    headerRow = next(csvReaderObj)          # 讀取文件下一行
    dates, highTemps, lowTemps = [], [], [] # 設定空串列
    for row in csvReaderObj:
        try:                    
            currentDate = datetime.strptime(row[0], "%Y/%m/%d")
            highTemp = int(row[1])          # 設定最高溫
            lowTemp = int(row[3])           # 設定最低溫
        except Exception:
            print('有缺值')
        else:
            highTemps.append(highTemp)      # 儲存最高溫
            lowTemps.append(lowTemp)        # 儲存最低溫
            dates.append(currentDate)       # 儲存日期
       
fig = plt.figure(dpi=80, figsize=(12, 8))   # 設定繪圖區大小
plt.plot(dates, highTemps)                  # 繪製最高溫
plt.plot(dates, lowTemps)                   # 繪製最低溫
plt.fill_between(dates, highTemps, lowTemps, color='y', alpha=0.2) # 填滿區間
fig.autofmt_xdate()                         # 日期旋轉
plt.title("Weather Report, Jan. 2017", fontsize=24)
plt.xlabel("", fontsize=14)
plt.ylabel("Temperature (C)", fontsize=14)
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

執行結果

參考資料

  • matplotlib(外連結) : 安裝指令=> pip install matplotlib , Matplotlib 是一個綜合性的套件,用於在 Python 中創建靜態、動畫和交互式可視化物件。
  • 標準函式庫 Index(外連結)
  • Python 第三方套件索引(外連結)
  • next() : 基本上,next() 函式會返回『迭代物件』的下一個元素,故我們若有許多元素儲存在 List 或是 Tuple 並想要使用 next() 函式讀出,則需使用 iter() 函式將其轉成可迭代物件。
  • enumerate() : 用來同時輸出索引與元素。enumerate() 是 Python 當中經常會看到的函式,其概念可說是非常簡單,就是 enumerate(iterable, start_index)。前者輸入一個可迭代的對象、比如說 List 資料型態;後者輸入開始的起點編號,為數字,若不設定時從 0 開始。

特色、摘要,Feature、Summary:

關鍵字、標籤,Keyword、Tag:

  • Python,Example-Project-Python,CSV,

留言

這個網誌中的熱門文章

Ubuntu 常用指令、分類與簡介

iptables的觀念與使用

網路設定必要參數IP、netmask(遮罩)、Gateway(閘道)、DNS

了解、分析登錄檔 - log

Python 與SQLite 資料庫

Blogger文章排版範本

Pandas 模組

如何撰寫Shell Script

查詢指令或設定 -Linux 線上手冊 - man

下載網頁使用 requests 模組