Python實現餅形圖的繪製
阿新 • • 發佈:2018-11-08
Python實現餅形圖的繪製:
餅形圖簡單介紹:
餅形圖yi般用一繪分型別資料的相對頻數或百分數頻數分佈,呈現部分與總體的關係。
繪製餅形圖的主要方法:
方法1:利用pandas中的Series.plot()或DataFrame.plot.pie()方法
方法2:利用matplotlib包中的呼叫axes.pie()方法
首先匯出需要的各種包,並準備好要用到的資料:
%matplotlib notebook import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns tips = pd.read_csv('examples/tips.csv')
tips的表結構如下圖所示:
對資料做初步處理:
# 以tips中的day列作為依據,對tips做分組處理
grouped = tips.groupby(tips['day'])
# 對分組資料進行統計求和
grouped_sum = grouped.sum()
grouped_sum的表結構表結構如下圖所示:
開始繪製餅形圖:
方法1具體事例:
Sereis.plot()示例:
fig,axes = plt.subplots() grouped_sum['total_bill'].plot(kind='pie',ax=axes,autopct='%.2f%%') # autopct引數的作用是指定餅形圖中資料標籤的顯示方式 # '%.2f%%'表示資料標籤的格式是保留兩位小數的百分數 axes.set_aspect('equal') # 設定餅圖的縱橫比相等 axes.set_title('Sum of total_bill grouped by day') plt.savefig('p1.png')
上述程式碼繪製的圖形為:
Series.plot()的用法具體參考:
DataFrame.plot.pie()示例:
fig,axes = plt.subplots() grouped_sum.plot.pie(y='tip',ax=axes,autopct='%.2f%%',legend=False, labeldistance=0.8) # autopct引數的作用是指定餅形圖中資料標籤的顯示方式 # '%.2f%%'表示資料標籤的格式是保留兩位小數的百分數 # labeldistance引數指定了每個扇形對應的標籤與圓心的距離 axes.set_aspect('equal') # 設定餅圖的縱橫比相等 axes.set_title('Sum of tip grouped by day') plt.savefig('p2.png')
上述程式碼繪製的圖形為:
DataFrame.plot.pie()的用法具體參考:
方法2具體示例:
axes.pie()示例:
fig,axes = plt.subplots()
axes.pie(grouped_sum['total_bill'],explode=[0.1,0,0,0],autopct='%.2f%%',
labels=['Fri','Sat','Sun','Thur'],startangle=90)
# explode引數指定了每個扇形與圓心偏移的距離,一般用於突出顯示某個扇形
# labels引數指定了每個扇形對應的標籤
# startangle=90表示餅圖的起始繪製角度是偏離x軸90度,並按逆時針繪製
axes.set_aspect('equal')
axes.set_title('Sum of total_bill grouped by day ')
plt.savefig('p3.png')
上述程式碼繪製的圖形為:
axes.pie()的用法具體參考:
其他參考資料:
《Python for Data Analysis》第二版
https://www.cnblogs.com/fat39/p/7159881.html
https://docs.python.org/3/library/string.html#grammar-token-conversion
PS:本文為博主原創文章,轉載請註明出處。