iT邦幫忙

0

[Python]資料視覺化M02─運用matplotlib完成圓餅圖(pie)

Hi! 大家好,我是Eric,上篇教大家如何用Python畫散布圖,這次來教大家畫圓餅圖。

/images/emoticon/emoticon31.gif


  • 緣起:台灣每天的車禍事故相當多,其中最嚴重的屬人員當場或24小時內死亡的A1事故,那造成這些嚴重事故的原因是甚麼呢?能不能從歷史資料中探索出甚麼線索呢?
  • 方法:運用 [Python]的[matplotlib] 套件。
  • 使用資料:警政署統計查詢網-A1類道路交通事故-按肇事原因分
  • 參考來源:plusone團隊-[Day20]Matplotlib資料視覺化進階!
    https://ithelp.ithome.com.tw/articles/10196239

1. 載入套件。

import pandas as pd               # 資料處理套件
import matplotlib.pyplot as plt   # 資料視覺化套件

2. 載入資料。

accident = pd.read_csv("number of car accident.csv")
accident.head(3)    # 顯示前3筆資料

https://ithelp.ithome.com.tw/upload/images/20190408/20115774Z7VVaPRsAT.png

3. 開始畫圖。

plt.figure(figsize=(6,9))    # 顯示圖框架大小

labels = accident["reason of car accident"]      # 製作圓餅圖的類別標籤
separeted = (0, 0, 0.3, 0, 0.3)                  # 依據類別數量,分別設定要突出的區塊
size = accident["count"]                         # 製作圓餅圖的數值來源

plt.pie(size,                           # 數值
        labels = labels,                # 標籤
        autopct = "%1.1f%%",            # 將數值百分比並留到小數點一位
        explode = separeted,            # 設定分隔的區塊位置
        pctdistance = 0.6,              # 數字距圓心的距離
        textprops = {"fontsize" : 12},  # 文字大小
        shadow=True)                    # 設定陰影

 
plt.axis('equal')                                          # 使圓餅圖比例相等
plt.title("Pie chart of car accident", {"fontsize" : 18})  # 設定標題及其文字大小
plt.legend(loc = "best")                                   # 設定圖例及其位置為最佳

plt.savefig("Pie chart of car accident.jpg",   # 儲存圖檔
            bbox_inches='tight',               # 去除座標軸占用的空間
            pad_inches=0.0)                    # 去除所有白邊
plt.close()      # 關閉圖表

4. 大功告成。
可以看出91.2%肇事原因皆是來自駕駛
https://ithelp.ithome.com.tw/upload/images/20190408/20115774DfpRFtpkLy.jpg

P.S. 本篇程式碼參考plusone團隊-[Day20]Matplotlib資料視覺化進階!,並利用網路實際的開放資料執行


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言