Python讀取CSV文件并進(jìn)行數(shù)據(jù)可視化繪圖
介紹:文件 sitka_weather_07-2018_simple.csv是阿拉斯加州錫特卡2018年1月1日的天氣數(shù)據(jù),其中包含當(dāng)天的最高溫度和最低溫度。數(shù)據(jù)文件存儲(chǔ)與data文件夾下,接下來用Python讀取該文件數(shù)據(jù),再基于數(shù)據(jù)進(jìn)行可視化繪圖。(詳細(xì)細(xì)節(jié)請看代碼注釋)
sitka_highs.py
import csv # 導(dǎo)入csv模塊
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/sitka_weather_07-2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # 返回文件的下一行,在這便是首行,即文件頭
# for index, column_header in enumerate(header_row): # 對列表調(diào)用了 enumerate()來獲取每個(gè)元素的索引及其值,方便我們提取需要的數(shù)據(jù)列
# print(index, column_header)
# 從文件中獲取最高溫度
dates, highs = [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
high = int(row[5])
dates.append(current_date)
highs.append(high)
# 根據(jù)最高溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red')
# 設(shè)置圖形的格式
ax.set_title("2018年7月每日最高溫度", fontproperties="SimHei", fontsize=24)
ax.set_xlabel('', fontproperties="SimHei", fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度(F)", fontproperties="SimHei", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()運(yùn)行結(jié)果如下:

設(shè)置以上圖標(biāo)后,我們來添加更多的數(shù)據(jù),生成一副更復(fù)雜的錫特卡天氣圖。將sitka_weather_2018_simple.csv數(shù)據(jù)文件置于data文件夾下,該文件包含整年的錫特卡天氣數(shù)據(jù)。
對代碼進(jìn)行修改:
sitka_highs.py
import csv # 導(dǎo)入csv模塊
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # 返回文件的下一行,在這便是首行,即文件頭
# for index, column_header in enumerate(header_row): # 對列表調(diào)用了 enumerate()來獲取每個(gè)元素的索引及其值,方便我們提取需要的數(shù)據(jù)列
# print(index, column_header)
# 從文件中獲取最高溫度
dates, highs = [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
high = int(row[5])
dates.append(current_date)
highs.append(high)
# 根據(jù)最高溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red')
# 設(shè)置圖形的格式
ax.set_title("2018年每日最高溫度", fontproperties="SimHei", fontsize=24)
ax.set_xlabel('', fontproperties="SimHei", fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度(F)", fontproperties="SimHei", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()運(yùn)行結(jié)果如下:

代碼再改進(jìn):雖然上圖已經(jīng)顯示了豐富的數(shù)據(jù),但是還能再添加最低溫度數(shù)據(jù),使其更有用
對代碼進(jìn)行修改:
sitka_highs_lows.py
import csv # 導(dǎo)入csv模塊
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # 返回文件的下一行,在這便是首行,即文件頭
# for index, column_header in enumerate(header_row): # 對列表調(diào)用了 enumerate()來獲取每個(gè)元素的索引及其值,方便我們提取需要的數(shù)據(jù)列
# print(index, column_header)
# 從文件中獲取日期、最高溫度和最低溫度
dates, highs, lows = [], [], []
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)
# 根據(jù)最高溫度和最低溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=0.5) # alpha指定顏色的透明度,0為完全透明
ax.plot(dates, lows, c='blue', alpha=0.5)
ax.fill_between(dates, highs, lows, facecolor='blue',alpha=0.1)
# 設(shè)置圖形的格式
ax.set_title("2018年每日最高溫度", fontproperties="SimHei", fontsize=24)
ax.set_xlabel('', fontproperties="SimHei", fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度(F)", fontproperties="SimHei", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()運(yùn)行結(jié)果如下:

此外,讀取CSV文件過程中,數(shù)據(jù)可能缺失,程序運(yùn)行時(shí)就會(huì)報(bào)錯(cuò)甚至崩潰。所有需要在從CSV文件中讀取值時(shí)執(zhí)行錯(cuò)誤檢查代碼,對可能的異常進(jìn)行處理,更換數(shù)據(jù)文件為:death_valley_2018_simple.csv ,該文件有缺失值。

對代碼進(jìn)行修改:
death_valley_highs_lows.py
import csv # 導(dǎo)入csv模塊
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/death_valley_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) # 返回文件的下一行,在這便是首行,即文件頭
# for index, column_header in enumerate(header_row): # 對列表調(diào)用了 enumerate()來獲取每個(gè)元素的索引及其值,方便我們提取需要的數(shù)據(jù)列
# print(index, column_header)
# 從文件中獲取日期、最高溫度和最低溫度
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
try:
high = int(row[5])
low = int(row[6])
except ValueError:
print(f"Missing data for {current_date}")
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
# 根據(jù)最高溫度和最低溫度繪制圖形
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=0.5) # alpha指定顏色的透明度,0為完全透明
ax.plot(dates, lows, c='blue', alpha=0.5)
ax.fill_between(dates, highs, lows, facecolor='blue',alpha=0.1)
# 設(shè)置圖形的格式
ax.set_title("2018年每日最高溫度和最低氣溫\n美國加利福利亞死亡谷", fontproperties="SimHei", fontsize=24)
ax.set_xlabel('', fontproperties="SimHei", fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("溫度(F)", fontproperties="SimHei", fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)
plt.show()如果現(xiàn)在運(yùn)行 death_valley_highs_lows.py,將會(huì)發(fā)現(xiàn)缺失數(shù)據(jù)的日期只有一個(gè):
Missing data for 2018-02-18 00:00:00
妥善地處理錯(cuò)誤后,代碼能夠生成圖形并忽略缺失數(shù)據(jù)的那天。運(yùn)行結(jié)果如下:

到此這篇關(guān)于Python讀取CSV文件并進(jìn)行數(shù)據(jù)可視化繪圖的文章就介紹到這了,更多相關(guān)Python讀取CSV內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python操作csv文件之csv.writer()和csv.DictWriter()方法的基本使用
- Python Pandas讀寫txt和csv文件的方法詳解
- Python 修改CSV文件實(shí)例詳解
- python讀取和保存為excel、csv、txt文件及對DataFrame文件的基本操作指南
- 利用python合并csv文件的方式實(shí)例
- Python中CSV文件(逗號(hào)分割)實(shí)戰(zhàn)操作指南
- python用pd.read_csv()方法來讀取csv文件的實(shí)現(xiàn)
- Python如何讀取csv文件時(shí)添加表頭/列名
- Python 比較兩個(gè) CSV 文件的三種方法并打印出差異
相關(guān)文章
Python3.2中的字符串函數(shù)學(xué)習(xí)總結(jié)
這篇文章主要介紹了Python3.2中的字符串函數(shù)學(xué)習(xí)總結(jié),本文講解了格式化類方法、查找 & 替換類方法、拆分 & 組合類方法等內(nèi)容,需要的朋友可以參考下2015-04-04
Python腳本實(shí)現(xiàn)一鍵自動(dòng)整理辦公文件
這篇文章主要介紹了Python實(shí)現(xiàn)腳本一鍵自動(dòng)整理辦公文件,文件下載文件夾就變得亂七八糟,整理的時(shí)候非常痛苦,巴不得有一個(gè)自動(dòng)化的工具幫我歸類文檔。下面小編就給大家分享自動(dòng)化整理文件的小技巧,需要的朋友可以參考一下文章內(nèi)容2022-02-02
CentOS 6.5中安裝Python 3.6.2的方法步驟
centos 6.5默認(rèn)自帶的python版本為2.6,而下面這篇文章主要給大家介紹了關(guān)于在CentOS 6.5中安裝Python 3.6.2的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12
王純業(yè)的Python學(xué)習(xí)筆記 下載
這篇文章主要介紹了王純業(yè)的Python學(xué)習(xí)筆記 下載2007-02-02
Python?matplotlib繪制散點(diǎn)圖配置(萬能模板案例)
這篇文章主要介紹了Python?matplotlib繪制散點(diǎn)圖配置(萬能模板案例),散點(diǎn)圖是指在??回歸分析???中,數(shù)據(jù)點(diǎn)在直角坐標(biāo)系平面上的?分布圖???,散點(diǎn)圖表示因變量隨??自變量???而?變化???的大致趨勢,據(jù)此可以選擇合適的函數(shù)??對數(shù)???據(jù)點(diǎn)進(jìn)行?擬合2022-07-07
Python tempfile模塊生成臨時(shí)文件和臨時(shí)目錄
這篇文章主要介紹了Python tempfile模塊生成臨時(shí)文件和臨時(shí)目錄,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09

