iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0

在資料分析的世界裡,Pandas 不只能整理資料,還能直接畫圖!
其實 Pandas 背後是透過 Matplotlib 來完成繪圖,所以不需要很複雜的設定,就能快速視覺化資料

1. 準備資料
首先建立一個簡單的成績資料表
https://ithelp.ithome.com.tw/upload/images/20251011/201788723Nhrz5VVxm.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251011/2017887265smrQFFGN.png

  • 先匯入 Pandas 套件,並將它縮寫為 pd,Pandas 是 Python 用來處理表格資料(像 Excel 表格)最常用的套件
  • 再建立一個字典,裡面有兩個鍵(key):"name" 和 "score"
  • pd.DataFrame(data) 是把字典轉換成 DataFrame,也就是 Pandas 的表格型資料
  • df 就是一個可以像 Excel 表格一樣操作的資料結構

2. 長條圖(bar chart)
Pandas 內建繪圖功能非常方便,一行就能搞定,加上這行 :
https://ithelp.ithome.com.tw/upload/images/20251011/20178872YC7QzL8Goo.png
結果就會輸出長條圖
https://ithelp.ithome.com.tw/upload/images/20251011/20178872keNnL0CgIT.png

  • kind="bar":指定圖表類型為長條圖
  • x、y:對應 DataFrame 欄位
  • legend=False:不顯示圖例(這裡只有一組資料,不需要圖例)

注意!
可能會遇到的問題1 : 如果在 Spyder(Anaconda 自帶的 IDE)裡執行後,發現沒有圖表出現的話,這種情況最常見的原因是「繪圖後端」設定的問題,那首先要做的就是 :

step1 到上方選單列「Tools(工具)」 → 「Preferences(偏好設定)」,點選完畢後會出現下方介面
https://ithelp.ithome.com.tw/upload/images/20251011/20178872tULDWR58cm.png
step2 左邊選 「IPython console」
https://ithelp.ithome.com.tw/upload/images/20251011/20178872rzAnE5zDwb.png
step3 點上方的 「Graphics」 分頁
https://ithelp.ithome.com.tw/upload/images/20251011/20178872pyoa492aAX.png
step4 將 Backend 改為:Automatic 或 Qt5,我自己的話是使用Qt5,不要選 Inline,因為這會讓圖顯示在 Console 裡,部分情況可能會沒反應
https://ithelp.ithome.com.tw/upload/images/20251011/20178872ZHn2ce1HfZ.png
完成後選擇「Apply」再「OK」,然後重新執行程式,就能顯示圖表了!

可能會遇到的問題2 : 還有可能出現的一個問題是,中文字標籤影響了 Matplotlib 的自動字型渲染,如果今天是把字典 "name" 裡的名字設為中文而不是英文的話,那麼圖表中的名字就會顯示不出來 :
https://ithelp.ithome.com.tw/upload/images/20251011/20178872t7WwtrrknZ.png
縱軸沒數字通常不是資料問題,而是Matplotlib 預設字型不支援中文,所以可能會影響刻度顯示,解決方法就是加上下方的這兩行程式碼 :
https://ithelp.ithome.com.tw/upload/images/20251011/20178872f3QhuvtZlx.png
就會看到圖表中縱軸的資料有顯示了
https://ithelp.ithome.com.tw/upload/images/20251011/20178872UnOVTflgfU.png

3. 折線圖(line chart)
如果想改成折線圖的話,只要加上這一行 :
https://ithelp.ithome.com.tw/upload/images/20251011/20178872FJwG7AyL02.png
結果就會輸出
https://ithelp.ithome.com.tw/upload/images/20251011/2017887215XF3ZhB4O.png

  • kind="line":改為折線圖
  • marker="o":讓折線上出現小圓點,更清楚每個節點的值

4. 圓餅圖(pie chart)
https://ithelp.ithome.com.tw/upload/images/20251011/20178872WLWaUd1W8V.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20251011/20178872uff43O1plu.png

  • set_index("name"):把name設為索引,這樣圖表上會顯示名字
  • autopct:設定百分比格式(保留一位小數)

5. 補充:更多圖表類型
Pandas plot(kind="...") 常見圖表類型
line : 折線圖 ( 預設圖表,適合顯示趨勢 )
bar / barh : 長條 / 橫條圖 ( 顯示分類數值比較 )
pie : 圓餅圖 ( 顯示比例 )
hist : 直方圖 ( 顯示分佈情況 )
box : 盒狀圖 ( 顯示統計分佈(中位數等) )
scatter : 散佈圖 ( 顯示兩變數關係 )


上一篇
Day26 : Python 使用 pandas 處理表格資料
系列文
學會 Python 不可怕:我每天學一點的 30 天筆記27
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言