# 圓餅圖製作 ```python= import matplotlib.pyplot as plt x = [1,2,3,4,5] plt.pie(x, radius=1.5, labels=x) plt.show() ``` 額外設定 pie() 的參數,就能讓圓餅圖有更多變化,下方的例子加入了 :::success * 1.explode 往外延伸 * 2.startangle 起始角度 * 3.textprops 文字樣式設定。 ::: ```python= import matplotlib.pyplot as plt x = [1,2,3,4,5] e = [0,0,0,0,0.1] plt.pie(x, radius=1.5, labels=x, explode=e, startangle=60, textprops={'weight':'bold','size':16}) plt.show() ``` :::info * 1.設定 autopct 參數後,會自動計算個別資料在總資料裡所佔的百分比。 * 2.並顯示計算後的百分比,預設使用「串格式化 %」的方式呈現。 ::: ```python= import matplotlib.pyplot as plt x = [1,2,3,4,5] plt.pie(x, radius=1.5, labels=x, autopct='%.1f%%') # %.1f%% 表示顯示小數點一位的浮點數,後方加上百分比符號 plt.show() ``` ## 使用 lambda 匿名函式,將百分比數值的後方加上原本的資料內容,再搭配文字的樣式設定,做出更清楚的圖表。 ```python= import matplotlib.pyplot as plt x = [1,2,3,4,5] def func(s,d): t = int(round(s/100.*sum(d))) # 透過百分比反推原本的數值 return f'{s:.1f}%\n( {t}ml )' # 使用文字格式化的方式,顯示內容 plt.pie(x, radius=1.5, textprops={'color':'w', 'weight':'bold', 'size':12}, # 設定文字樣式 pctdistance=0.8, autopct=lambda i: func(i,x), wedgeprops={'linewidth':3,'edgecolor':'w'}) # 繪製每個扇形的外框 plt.show() ``` ## 字體 ```python= import matplotlib.pyplot as plt import matplotlib.pyplot # 先下載台北思源黑體字型 !wget -O taipei_sans_tc_beta.ttf https://drive.google.com/uc?id=1eGAsTN1HBpJAkeVM57_C7ccp7hbgSz3_&export=download import matplotlib matplotlib.font_manager.fontManager.addfont('taipei_sans_tc_beta.ttf') matplotlib.rc('font', family='Taipei Sans TC Beta') ``` ## 挑戰8 ```python= import matplotlib.pyplot as plt x = [1,2,3,4,5] y = ['蘋果','檸檬','柳橙','香蕉','奇異果'] pictures,y_text,percent_text = plt.pie( x, labels=y, autopct='%0.2f%%', center=(-10,0), shadow=False ) plt.title("水果圓餅圖",x=0.5, y=1.03) plt.show() ``` * 成果 ![image](https://hackmd.io/_uploads/BkbV-sqQ1e.png) ## 進階挑戰9 ```python= import matplotlib import matplotlib.pyplot as plt x = ['蘋果','檸檬','柳橙','香蕉','奇異果'] y = [800,300,1200,1800,700] # 設定圓餅圖大小 plt.figure(figsize=(8,6)) # 依據類別數量,分別設定要突出的距離 c = (0, 0.1, 0, 0, 0) def func(s,d): t = int(round(s/100.*sum(d))) return f'{s:.1f}%\n( {t}公噸 )' # 設定圓餅圖屬性 pictures,y_text,percent_text = plt.pie(y, labels = x, explode = c, pctdistance = 0.8, radius = 1.3, autopct=lambda i: func(i,y), wedgeprops={'linewidth':3,'edgecolor':'w'}, center = (-10,0), shadow=False ) plt.legend(loc = "center right") plt.title("水果圓餅圖", x=0.5, y=1.03) plt.show() ``` * 成果 ![image](https://hackmd.io/_uploads/rkeL-i97kx.png) ## 1.載入函數庫 * import matplotlib 要進行本篇的範例,必須先載入 matplotlib 函式庫的 pyplot 模組,範例將其獨立命名為 plt。 ```python= import matplotlib.pyplot as plt ``` ## 程式碼連結 [Colab](https://colab.research.google.com/drive/1RKPFtdQH9tEcOiKgFaVrWZ8AU3KGMMHk#scrollTo=IpV3aJcVEpZd&line=1&uniqifier=1)