matplotlib---饼图

作用

饼图:用于表示不同分类的占比情况,通过弧度大小来对比各种分类。

特点:分类数据的占比情况(占比)

函数

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, rotatelabels=False, hold=None, data=None)

部分参数解释:
x :(每一块)的比例,如果sum(x) > 1会使用sum(x)归一化;

labels :(每一块)饼图显示的说明文字;
labeldistance :label标记的绘制位置,相对于半径的比例,默认值为1.1, 如<1则绘制在饼图内侧;

explode :(每一块)离开中心距离;

startangle :起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起;

shadow :在饼图下面画一个阴影。默认值:False,即不画阴 影;

autopct :控制饼图内百分比设置,可以使用format字符串或者format function
'%1.1f’指小数点前后位数(没有用空格补齐);
pctdistance :类似于labeldistance,指定autopct的位置刻度,默认值为0.6;

radius :控制饼图半径,默认值为1;

counterclock :指定指针方向;布尔值,可选参数,默认为:True,即逆时针。将值改为False即可改为顺时针。

wedgeprops :字典类型,可选参数,默认值:None。参数字典传递给wedge对象用来画一个饼图。例如:wedgeprops={‘linewidth’:3}设置wedge线宽为3。

textprops :设置标签(labels)和比例文字的格式;字典类型,可选参数,默认值为:None。传递给text对象的字典参数。

pie各参数示例

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签

labels = 'A','B','C','D'
sizes = [10,10,10,70]
plt.pie(sizes,labels=labels)

plt.title("饼图详解示例")
plt.show()

matplotlib---饼图_第1张图片
1、x:每一块饼图的比例,为必填项,如果sum(x)>1,会将多出的部分进行均分;

sizes = [10,10,30,40]  #总和不是100也可以
plt.pie(sizes,labels = labels)
plt.show()

matplotlib---饼图_第2张图片
当用百分比表示,但总和小于1时,pie() 不会进行归一化,而是直接绘制出缺失一个类别的饼状图(除了0.1、0.5、0.2三个类别外,应剩余一个0.20.2的类别,以空白区绘制):

sizes = [0.1,0.5,0.2]
plt.pie(sizes,labels = ['a','b','c'])
plt.show()

matplotlib---饼图_第3张图片

2、labels : 每一块饼图外侧显示的说明文字;

sizes = [10,10,30,40]
labels = ['Mon','Tue','Fri','Sun']
plt.pie(sizes,labels = labels)
plt.show()

matplotlib---饼图_第4张图片
3.labeldistance : label绘制位置,相对于半径的比例, 如<1则绘制在饼图内侧,默认值为1.1

sizes = [10,10,30,40]
labels = ['Mon','Tue','Fri','Sun']
plt.pie(sizes,labels = labels,labeldistance=0.6)
plt.show()

matplotlib---饼图_第5张图片

4、explode : 每一块饼图 离开中心距离,默认值为(0,0),就是不离开中心;

sizes = [10,10,30,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.2,0,0]
plt.pie(sizes,labels=labels,explode=explode)
plt.show()

matplotlib---饼图_第6张图片
5、colors:数组,可选参数,默认为:None;用来标注每块饼图的matplotlib颜色参数序列。如果为None,将使用当前活动环的颜色。

sizes = [10,10,30,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.2,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors)
plt.show()

matplotlib---饼图_第7张图片
6、shadow :是否阴影,默认值为False,即没有阴影,在这里,将其改为True

sizes = [10,10,30,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.2,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,shadow = True)
plt.show()

matplotlib---饼图_第8张图片
7.autopct :控制饼图内百分比设置,可以使用format字符串或者format function;
‘%.1f’:指小数点后保留一位有效数值,结果四舍五入;

sizes = [11,34,23,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.1,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,shadow = True,autopct='%.1f')
plt.show()

matplotlib---饼图_第9张图片
保留两位小数,并增加百分号。

sizes = [11,34,23,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.1,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,shadow = True,autopct='%.2f%%')
plt.show()

运行代码之后,得到的结果
matplotlib---饼图_第10张图片
8、startangle :起始绘制角度,默认图是从x轴正方向逆时针画起
如设定startangle=90则从y轴正方向画起;

sizes = [11,34,23,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.1,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,shadow = True,autopct='%.2f%%',startangle=90)
plt.show()

matplotlib---饼图_第11张图片
9、counterclock:指定指针方向;布尔值,可选参数,默认为:True,即逆时针。
将值改为False(顺时针)。

sizes = [11,34,23,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.1,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,shadow = True,autopct='%.2f%%',startangle=90,counterclock=False)
plt.show()

matplotlib---饼图_第12张图片
10.radius :控制饼图半径;浮点类型,可选参数,默认为:None(1)。

sizes = [11,34,23,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.1,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,
        shadow = True,autopct='%.2f%%',startangle=90,counterclock=False,
        radius=1.5)
plt.show()

matplotlib---饼图_第13张图片
11、textprops :设置标签(labels)和比例文字的格式;字典类型,可选参数,默认值为:None。

sizes = [11,34,23,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.1,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,
        shadow = True,autopct='%.2f%%',startangle=90,counterclock=False,radius=1.5,
       textprops={'color':'b','fontsize':'12'})
plt.show()

matplotlib---饼图_第14张图片
12、将饼图显示为正圆形
plt.axis( );

sizes = [11,34,23,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.1,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,
        shadow = True,autopct='%.2f%%',startangle=90,counterclock=False,radius=1.5,
       textprops={'color':'b','fontsize':'12'})
plt.axis()
plt.show()

13、添加图例
plt.legend( );

注意:plt.legend()中除了大家熟悉的控制位置的loc外,还有一个控制位置的重要参数:bbox_to_anchor(num1, num2), bbox_to_anchor被赋予的二元组中,第一个数值用于控制legend的左右移动,值越大越向右边移动,第二个数值用于控制legend的上下移动,值越大,越向上移动。

sizes = [11,34,23,40]
labels = ['Mon','Tue','Fri','Sun']
explode = [0,0.1,0,0]
colors = ['g','r','y','c']
plt.pie(sizes,labels=labels,explode=explode,colors=colors,
        shadow = True,autopct='%.2f%%',startangle=90,counterclock=False,radius=1.5,
       textprops={'color':'b','fontsize':'12'})
plt.axis()

plt.legend(bbox_to_anchor=(1,1),title='图例',fontsize=15)  #fontsize只能修改图例内字体的大小,但不能修改标题大小
plt.rcParams.update({'font.size': 20}) #修改图例;标题大小
plt.show()

matplotlib---饼图_第15张图片
14、Bar of pie

import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np

# make figure and assign axis objects
fig = plt.figure(figsize=(9, 5.0625))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
fig.subplots_adjust(wspace=0)

# pie chart parameters(子图一画饼图)
ratios = [.27, .56, .17]
labels = ['Approve', 'Disapprove', 'Undecided']
explode = [0.1, 0, 0]
# rotate so that first wedge is split by the x-axis
angle = -180 * ratios[0]
ax1.pie(ratios, autopct='%1.1f%%', startangle=angle,
        labels=labels, explode=explode)

# bar chart parameters(子图二画柱形图)

xpos = 0
bottom = 0
ratios = [.33, .54, .07, .06]
width = .2
colors = [[.1, .3, .5], [.1, .3, .3], [.1, .3, .7], [.1, .3, .9]]

for j in range(len(ratios)):
    height = ratios[j]
    ax2.bar(xpos, height, width, bottom=bottom, color=colors[j])
    ypos = bottom + ax2.patches[j].get_height() / 2
    bottom += height
    ax2.text(xpos, ypos, "%d%%" % (ax2.patches[j].get_height() * 100),
             ha='center')

ax2.set_title('Age of approvers')
ax2.legend(('50-65', 'Over 65', '35-49', 'Under 35'),bbox_to_anchor=(1,1))
ax2.axis('off')
ax2.set_xlim(- 2.5 * width, 2.5 * width)

# use ConnectionPatch to draw lines between the two plots
# get the wedge data
theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2
center, r = ax1.patches[0].center, ax1.patches[0].r
bar_height = sum([item.get_height() for item in ax2.patches])

# draw top connecting line
x = r * np.cos(np.pi / 180 * theta2) + center[0]
y = np.sin(np.pi / 180 * theta2) + center[1]
con = ConnectionPatch(xyA=(- width / 2, bar_height), xyB=(x, y),
                      coordsA="data", coordsB="data", axesA=ax2, axesB=ax1)
con.set_color([0, 0, 0])
con.set_linewidth(4)
ax2.add_artist(con)

#draw bottom connecting line
x = r * np.cos(np.pi / 180 * theta1) + center[0]
y = np.sin(np.pi / 180 * theta1) + center[1]
con = ConnectionPatch(xyA=(- width / 2, 0), xyB=(x, y), coordsA="data",
                      coordsB="data", axesA=ax2, axesB=ax1)
con.set_color([0, 0, 0])
ax2.add_artist(con)
con.set_linewidth(4)


plt.show()

代码不懂的地方:

  • ax2.patches[j].get_height() / 2
    解析:
    1.Artists分为简单类型和容器类型两种。简单类型的Artists为标准的绘图元件,例如Line2D、 Rectangle、 Text、AxesImage 等等。而容器类型则可以包含许多简单类型的Artists,使它们组织成一个整体,例如Axis、 Axes、Figure等。
    2.Figure是最大的一个Aritist,它包括整幅图像的所有元素,背景是一个Rectangle对象,用Figure.patch属性表示。
    通过调用add_subplot或者add_axes方法往图表中添加Axes(子图)。
    3.下面列出Axes的创建Artist对象的方法:

     Axes的方法   所创建的对象        添加进的列表
     annotate    Annotate            texts
     bars        Rectangle           patches
     errorbar    Line2D, Rectangle   lines,patches
     fill        Polygon             patches
     hist        Rectangle           patches
     imshow      AxesImage           images
     legend      Legend              legends
     plot        Line2D              lines
     scatter     PolygonCollection   Collections
     text        Text                texts
    

4.下面详细列出Axes包含各种Artist对象的属性:

artists : Artist对象列表
patch : 作为Axes背景的Patch对象,可以是Rectangle或者Circle
collections : Collection对象列表
images : AxesImage对象列表
legends : Legend对象列表
lines : Line2D对象列表
patches : Patch对象列表
texts : Text对象列表
xaxis : XAxis对象
yaxis : YAxis对象

所以通过上面四点可以知道for循环每循环一次,则ax2通过bar()方法,创建一个Rectangle对象,并加入到了axes的patches列表中,所以ax2.patches[j].get_height() / 2为取第j个Rectangle对象,并获取其高度,之后/2,即取高度的一半。

  • ConnectionPatch(xyA=(- width / 2, bar_height), xyB=(x, y), coordsA=“data”, coordsB=“data”, axesA=ax2, axesB=ax1)
    1.A ConnectionPatch class is to make connecting lines between two points (possibly in different axes).

Connect point xyA in coordsA with point xyB in coordsB

matplotlib---饼图_第16张图片

15、嵌套饼图(甜甜圈饼图)
甜甜圈形状的效果是通过楔形道具的论点,在馅饼的楔形部分设置宽度来实现的。

代码:

 fig, ax = plt.subplots()

 size = 0.3
 vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
 # 通过get_cmap获取颜色,tab20c和tab20b三种颜色 ,所以outer_colors       为camp(np.arange(3))
 cmap = plt.get_cmap("tab20c")
 outer_colors = cmap(np.arange(3)*4)  #0,4,8
 inner_colors = cmap(np.array([1, 2,5,6, 9, 10]))  #颜色可自己调节,赋予方向为逆时针方向

 #radius :控制饼图半径,默认值为1;
 #vals.sum(axis=1)为[92. 77. 39.]

 ax.pie(vals.sum(axis=1), radius=1,       colors=outer_colors,wedgeprops=dict(width=size, edgecolor='w'))

 #vals.flatten()为[60. 32. 37. 40. 29. 10.]
 ax.pie(vals.flatten(), radius=1-size,    colors=inner_colors,wedgeprops=dict(width=size, edgecolor='w'))

 ax.set(aspect="equal", title='Pie plot with `ax.pie`')
 plt.show()

matplotlib---饼图_第17张图片

你可能感兴趣的:(Python数据分析)