相较散点图和折线图,柱状图、饼图、箱线图是另外 3 种数据分析常用的图形,主要用于分析数据内部的分布状态或分散状态。饼图主要用于查看各分组数据在总数据中的占比。
Matplotlib 中绘制饼图的函数为 pie () ,使用语法如下:
plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False)
import pandas as pd
import matplotlib.pyplot as plt
#读取数据
datafile = u'D:\\pythondata\\learn\\matplotlib.xlsx'
data = pd.read_excel(datafile)
#取dataframe中的最后一行的数据画饼图
x = data[data['时间']==2018].iloc[:,1:].values.tolist()[0]
plt.figure(figsize=(5,5))#设置画布的尺寸
plt.title('Examples of Pie Graph',fontsize=20)#标题,并设定字号大小
labels = 'Jay income','JJ income','Jolin income','Hannah income'#图例
colors = ['hotpink','slateblue','goldenrod','olivedrab']
#startangle:从90度的位置开始画第一个饼图;autopct:显示一位小数;其他参数使用默认值
plt.pie(x,labels=labels,colors = colors, startangle=90,autopct='%1.1f%%')
plt.show()#显示图像
通过参数 explode 来实现:
import pandas as pd
import matplotlib.pyplot as plt
#读取数据
datafile = u'D:\\pythondata\\learn\\matplotlib.xlsx'
data = pd.read_excel(datafile)
#取dataframe中的最后一行的数据画饼图
x = data[data['时间']==2018].iloc[:,1:].values.tolist()[0]
plt.figure(figsize=(5,5))#设置画布的尺寸
plt.title('Examples of Pie Graph',fontsize=20)#标题,并设定字号大小
labels = 'Jay income','JJ income','Jolin income','Hannah income'#图例
colors = ['hotpink','slateblue','goldenrod','olivedrab']
explodes = (0,0,0.1,0)#突出显示Jolin income这部分的饼图
plt.pie(x,explode = explodes, labels=labels,colors = colors, startangle=90,autopct='%1.1f%%')
plt.show()#显示图像
import pandas as pd
import matplotlib.pyplot as plt
#读取数据
datafile = u'D:\\pythondata\\learn\\matplotlib.xlsx'
data = pd.read_excel(datafile)
#取dataframe中的最后一行的数据画饼图
x = data[data['时间']==2018].iloc[:,1:].values.tolist()[0]
x_0 = [1,0,0,0]#用于显示空心
plt.figure(figsize=(5,5))#设置画布的尺寸
labels = 'Jay income','JJ income','Jolin income','Hannah income'#图例
colors = ['hotpink','slateblue','goldenrod','olivedrab']
plt.pie(x , radius=1.0,pctdistance = 0.8,labels=labels,colors = colors, startangle=90,autopct='%1.1f%%')
plt.pie(x_0, radius=0.6,colors = 'w')
plt.show()#显示图像
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
datafile = u'D:\\pythondata\\learn\\matplotlib.xlsx'
data = pd.read_excel(datafile)
x1 = data[data['时间']==2005].iloc[:,1:].values.tolist()[0]#多重饼图第一层数据
x2 = data[data['时间']==2010].iloc[:,1:].values.tolist()[0]#多重饼图第二层数据
fig,ax = plt.subplots()
colors = ['hotpink','slateblue','goldenrod','olivedrab']
labels = 'Jay income','JJ income','Jolin income','Hannah income'#图例
pie_1 = ax.pie(x1,startangle=90,autopct='%1.1f%%',radius=1.5,pctdistance = 0.9,colors=colors, labels=labels)
pie_2 = ax.pie(x2,startangle=90,autopct='%1.1f%%',radius=1.2,pctdistance = 0.6,colors=colors)
#添加多重饼图的分割线
for pie_wedge in pie_1[0]:
pie_wedge.set_edgecolor('black')
for pie_wedge in pie_2[0]:
pie_wedge.set_edgecolor('black')
ax.set(aspect="equal")
plt.show()#显示图表