跳到主要內容

[Pandas教學]資料視覺化必懂的Pandas套件繪製Matplotlib分析圖表實戰

pandas_and_matplotlib

資料分析一詞相信大家耳熟能詳,目的就是將蒐集到的大量數據,經過有效整理及分析後,來洞悉其中的價值,進而提供更好的用戶體驗或是預測未來的趨勢。

而資料視覺化就是其中一種幫助資料分析師觀察數據的方式,這部份剛好在筆者近期所上過的「Python 金融資訊爬蟲大師班」線上課程有學到,所以本文就來應用所學,利用Pandas套件讀取政府開放資料平台-歷年國內主要觀光遊憩據點遊客人數月別統計的CSV檔案資料,進行篩選整理,並且結合Matplotlib套件將資料視覺化,藉此來看看哪一個觀光景點最多人去。實作步驟如下:

  • 安裝Pandas及Matplotlib
  • 篩選Pandas DataFrame資料集
  • 繪製Matplotlib圖表
  • 解決Matplotlib無法顯示中文字問題

一、安裝Pandas及Matplotlib

Matplotlib是一個Python的圖表繪製套件,可以用來建立各種不同的圖表,像是折線圖、長條圖與圓餅圖等,並且能夠依需求客製化顯示,而Pandas套件內建了Matplotlib套件的繪圖方法(Method),讓開發人員能夠直接利用Pandas DataFrame來建立圖表。

首先,開啟Visual Studio Code,建立一個資料夾與app.py檔案,接著,在Terminal視窗中,利用以下指令來安裝Pandas及Matplotlib套件:

$ pip install pandas

$ pip install matplotlib

既然Pandas套件已經含有Matplotlib套件的繪圖方法(Method),為什麼還要再安裝Matplotlib套件呢?這是因為Pandas套件只有繪圖功能,之後的圖表顯示和更多的客製化,就需要仰賴Matplotlib套件的幫忙。

接下來,前往政府開放資料平台-歷年國內主要觀光遊憩據點遊客人數月別統計,下載CSV檔案資料,並且存放在資料夾中,如下圖:

pandas_and_matplotlib

而其中的資料內容如下圖:

pandas_and_matplotlib

二、篩選Pandas DataFrame資料集

有了CSV檔案資料後,就可以開啟app.py檔案,利用Pandas套件的read_csv()方法(Method)來進行讀取,如下範例:

import pandas as pd


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

由於這個CSV檔案是使用big5編碼,所以範例中需使用encoding關鍵字參數來進行指定,否則會出現亂碼。

假設本文想要來分析2019年臺北市第一季(1~3月)各景點的旅客人數,這時候,就需要對Pandas DataFrame讀取到的CSV資料來進行篩選,如下範例:

import pandas as pd


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

rows = (df['年別'] == 2019) & (df['縣市別'] == '臺北市')
columns = ['細分', '1月', '2月', '3月']
result = df.loc[rows, columns].head(10)
print(result)

執行結果

pandas_and_matplotlib
以上範例使用了Pandas套件的loc[rows, colums]語法來選擇所需的資料集,分別是第6行利用邏輯運算語法選擇2019年臺北市的列(rows)資料,以及第7行的「細分(景點名稱)」、「1月」、「2月」、「3月」欄位(columns)。其中為了讓教學簡單易懂,所以只取前10筆資料。

在Pandas套件繪製圖表時,x軸會使用Pandas DataFrame的索引值(index)來顯示,這時候範例中的數字索引值(index)就會降低可讀性,因為在圖表上無法一眼看出這個索引值(index)是對應到哪一個「細分(景點名稱)」。

所以,就需要呼叫Pandas套件的set_index()方法(Method)來重新指定想要的索引值(index)欄位,也就是「細分(景點名稱)」,並且設定inplace=True取代原索引值(index),如下範例:

import pandas as pd


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

rows = (df['年別'] == 2019) & (df['縣市別'] == '臺北市')
columns = ['細分', '1月', '2月', '3月']
result = df.loc[rows, columns].head(10)
result.set_index('細分', inplace=True)
print(result)

執行結果

pandas_and_matplotlib

三、繪製Matplotlib圖表

Pandas DataFrame資料集準備好後,就可以來繪製圖表了,而為了要顯示與客製化圖表,就需要引用Matplotlib模組(Module),如下範例第2行:

import pandas as pd
import matplotlib.pyplot as plt


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

rows = (df['年別'] == 2019) & (df['縣市別'] == '臺北市')
columns = ['細分', '1月', '2月', '3月']
result = df.loc[rows, columns].head(10)
result.set_index('細分', inplace=True)

接下來,利用Pandas DataFrame的plot()繪圖方法(Method),設定圖表的標題、x、y軸說明文字、圖例及大小,完成後,呼叫Matplotlib模組(Module)的show()方法(Method)來進行顯示,如下範例:

import pandas as pd
import matplotlib.pyplot as plt


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

rows = (df['年別'] == 2019) & (df['縣市別'] == '臺北市')
columns = ['細分', '1月', '2月', '3月']
result = df.loc[rows, columns].head(10)
result.set_index('細分', inplace=True)

chart = result.plot(title='2019年臺北市各景點旅客人數',  #圖表標題
                    xlabel='細分(景點名稱)',  #x軸說明文字
                    ylabel='人數',  #y軸說明文字
                    legend=True,  # 是否顯示圖例
                    figsize=(10, 5))  # 圖表大小
plt.show()

執行結果

pandas_and_matplotlib

從執行結果可以看到中文字無法正常的顯示,是因為沒有設定字型的關係,這部分等一下會來和大家分享如何解決。

除此之外,Pandas套件的plot()繪圖方法(Method)預設為折線圖,如果想要繪製其它的圖表,例如長條圖,則可以設定kind關鍵字參數為bar,如下範例:

import pandas as pd
import matplotlib.pyplot as plt


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

rows = (df['年別'] == 2019) & (df['縣市別'] == '臺北市')
columns = ['細分', '1月', '2月', '3月']
result = df.loc[rows, columns].head(10)
result.set_index('細分', inplace=True)

chart = result.plot(kind='bar',  #圖表類型
		    title='2019年臺北市各景點旅客人數',  #圖表標題
                    xlabel='細分(景點名稱)',  #x軸說明文字
                    ylabel='人數',  #y軸說明文字
                    legend=True,  # 是否顯示圖例
                    figsize=(10, 5))  # 圖表大小
plt.show()
執行結果
pandas_and_matplotlib

更多圖表的類型(kind)可以參考Pandas官方文件。

四、解決Matplotlib無法顯示中文字問題

最後,就要來設定字型解決Matplotlib套件無法顯示中文字的問題,本文以Google Noto Fonts字型為例,在搜尋的地方輸入「Noto Sans CJK TC」關鍵字,並且下載字型,如下圖:

pandas_and_matplotlib

解壓縮後選擇其中一種字型檔放入本文所建立的資料夾中,如下圖:

pandas_and_matplotlib

開啟app.py檔案,引用Matplotlib套件的FontProperties(字型屬性)模組(Module),如下範例第3行:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

rows = (df['年別'] == 2019) & (df['縣市別'] == '臺北市')
columns = ['細分', '1月', '2月', '3月']
result = df.loc[rows, columns].head(10)
result.set_index('細分', inplace=True)

chart = result.plot(title='2019年臺北市各景點旅客人數',  #圖表標題
                    xlabel='細分(景點名稱)',  #x軸說明文字
                    ylabel='人數',  #y軸說明文字
                    legend=True,  # 是否顯示圖例
                    figsize=(10, 5))  # 圖表大小

plt.show()

有了FontProperties(字型屬性)模組(Module),就能夠設定剛剛所下載的字型,如下範例第19行:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

rows = (df['年別'] == 2019) & (df['縣市別'] == '臺北市')
columns = ['細分', '1月', '2月', '3月']
result = df.loc[rows, columns].head(10)
result.set_index('細分', inplace=True)

chart = result.plot(title='2019年臺北市各景點旅客人數',  #圖表標題
                    xlabel='細分(景點名稱)',  #x軸說明文字
                    ylabel='人數',  #y軸說明文字
                    legend=True,  # 是否顯示圖例
                    figsize=(10, 5))  # 圖表大小

font = FontProperties(fname=r'NotoSansCJKtc-Medium.otf')

plt.show()

接著,將第13行進行改寫,有顯示中文字的地方另外設定字型,如下範例第17~23行:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties


df = pd.read_csv('歷年國內主要觀光遊憩據點遊客人數月別統計.csv', encoding='big5')

rows = (df['年別'] == 2019) & (df['縣市別'] == '臺北市')
columns = ['細分', '1月', '2月', '3月']
result = df.loc[rows, columns].head(10)
result.set_index('細分', inplace=True)

chart = result.plot(figsize=(10, 5))  # 圖表大小

font = FontProperties(fname=r'NotoSansCJKtc-Medium.otf')

for label in chart.get_xticklabels():
    label.set_fontproperties(font)  # 設定x軸每一個細分(景點名稱)字型

plt.title('2019年臺北市各景點旅客人數', fontproperties=font)  #圖表標題
plt.xlabel('細分(景點名稱)', fontproperties=font)  #x軸說明文字
plt.ylabel('人數', fontproperties=font)  #y軸說明文字
plt.legend(prop=font)  #圖例

plt.show()

執行結果

pandas_and_matplotlib

五、小結

以上就是在「Python 金融資訊爬蟲大師班」線上課程所學到的Pandas套件繪製Matplotlib圖表的方法,老師為Kadin Chung 鍾榮達,課程中從Python的基礎語法教起,接著,以金融領域為例,帶大家瞭解如何使用BeautifulSoup與Selenium來實作網頁爬蟲,取得股市公開資料,並且存入資料庫與檔案,最後使用Pandas套件進行資料分析,筆者覺得非常適合初學者,實作的步調不會過於緊湊複雜,淺顯易懂,讓學生能夠很容易的吸收,給大家參考。

如果您喜歡我的文章,請幫我按五下Like(使用Google或Facebook帳號免費註冊),支持我創作教學文章,回饋由LikeCoin基金會出資,完全不會花到錢,感謝大家。


有想要看的教學內容嗎?歡迎利用以下的Google表單讓我知道,將有機會成為教學文章,分享給大家😊

    Python網頁爬蟲-Scrapy教學
    Python非同步網頁爬蟲
    Python網頁爬蟲應用
    Python網頁爬蟲部署
    Python網頁爬蟲資料儲存
    Python網頁爬蟲技巧








    留言

    張貼留言