白话解读matplotlib用法-饼图
前情提要
白话解读matplotlib用法-通用函数和柱状图、白话解读matplotlib用法-直方图、白话解读matplotlib用法-在柱子上添加数据、白话解读matplotlib用法-折线图
大家好,我是W
前言:前面已经讲到折线图了,接下来将饼图。
饼图
饼图介绍和使用场景
介绍
饼图顾名思义就是使用一块像饼一样的圆盘进行切分出不同的比例,最终向观众展示出不同成分所占比例的大小。**他所侧重的是一个系统内的不同组成、部分所占总系统的比重。**他既可以表现出各个组成部分的比例关系,也能表现一个组成部分占总体的比例。
使用场景
- 2020年各行业GDP占全国GDP的比重
- 某米IOT战略下各板块营收情况
- 某用户每天使用各手机App时长占比
…
实例讲解(代码复制可用)
还是按照老规矩,我们先画出一个简单的图,然后调参数来学习。
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
# 标签列表 饼图上的每一块对应一个标签
labels = ['Java', 'C', 'C++', 'Python', 'Visual Basic.NET', 'C#', 'PHP', 'JavaScript', 'SQL', 'Assembly langugage',
'其他']
# size列表,表示每一个标签对应的比例,可以是浮点小数,也可以是列表总数不超过一百的数
size = [0.16881, 0.14966, 0.07471, 0.06992, 0.04762, 0.03541, 0.02925, 0.02411, 0.02316, 0.01409, 0.36326]
# 间隔列表,表示每一个标签块离开圆心的长度
explode = [0.1 for i in range(11)]
# 使用pie来将数据丢进去
# 我们使用的三个参数都是列表形式 且块与列表下标一一对应
plt.pie(size, explode=explode, labels=labels)
plt.show()
效果图:
这三个参数都比较容易理解,接下来我们看看其他参数。
Parameters
这是官方文档的参数解释,我给大家一个个翻
----------
x : array-like
The wedge sizes.
# x:可迭代对象,里面的值是块的size
explode : array-like, optional, default: None
If not *None*, is a ``len(x)`` array which specifies the fraction
of the radius with which to offset each wedge.
# explode:可迭代对象,这个参数是可选参数,默认为None
# 非空时,其列表或元祖长度应为x的长度
# 这个列表给出每一个碎片(块)离圆心的距离
labels : list, optional, default: None
A sequence of strings providing the labels for each wedge
# labels:列表对象,可选的,默认为None
# 一系列的字符串,用于标出每一块代表的含义
colors : array-like, optional, default: None
A sequence of matplotlib color args through which the pie chart
will cycle. If *None*, will use the colors in the currently
active cycle.
# colors:可迭代对象,可选的,默认为None
# 这个colors列表长度跟x长度一致,且使用matplotlib里的颜色符号
# 若未None的时候会自动上色
autopct : None (default), string, or function, optional
If not *None*, is a string or function used to label the wedges
with their numeric value. The label will be placed inside the
wedge. If it is a format string, the label will be ``fmt%pct``.
If it is a function, it will be called.
# autopct: 默认为None,字符串或是一个函数,可选的
# 非空时,应传入一个字符串或者函数,用于标出每一个块的大小值
# 这个值会被标在每个三角块的内部
# 若传入的是字符串形式,他会被格式化,若为函数将会被调用
# 控制饼图内百分比设置,可以使用format字符串或者format function
# '%1.1f'指小数点前后位数(没有用空格补齐)
pctdistance : float, optional, default: 0.6
The ratio between the center of each pie slice and the start of
the text generated by *autopct*. Ignored if *autopct* is *None*.
# pctdistance:浮点型,可选的 ,默认为0.6
# 表示每一个三角块之间的比例,且文本由autopct生成,当autopct为空时传入无效
shadow : bool, optional, default: False
Draw a shadow beneath the pie.
# shadow:布尔类型,可选,默认空
# 在饼图下方画阴影
labeldistance : float or None, optional, default: 1.1
The radial distance at which the pie labels are drawn.
If set to ``None``, label are not drawn, but are stored for use in
``legend()``
# labeldistance:浮点型或空,可选的,默认是1.1
# 每一个饼图标签的辐射距离 为空时,标签不会被画上,而是被存储在legend()里等待被调用
startangle : float, optional, default: None
If not *None*, rotates the start of the pie chart by *angle*
degrees counterclockwise from the x-axis.
# startangle:浮点型,可选的,默认空
# 非空时 从x轴开始逆时针旋转饼图传入的度数
radius : float, optional, default: None
The radius of the pie, if *radius* is *None* it will be set to 1.
# radius:半径 ,默认为1
counterclock : bool, optional, default: True
Specify fractions direction, clockwise or counterclockwise.
# counterclock:标出碎片的角度,顺时针还是逆时针
wedgeprops : dict, optional, default: None
Dict of arguments passed to the wedge objects making the pie.
For example, you can pass in ``wedgeprops = {'linewidth': 3}``
to set the width of the wedge border lines equal to 3.
For more details, look at the doc/arguments of the wedge object.
By default ``clip_on=False``.
# wedgeprops:字典
# 传入一个字典去设置饼图的参数,比如传入```wedgeprops = {'linewidth':3}```来设置饼图的边宽
textprops : dict, optional, default: None
Dict of arguments to pass to the text objects.
# textprops:字典
# 参数字典,用于设置字体对象
center : list of float, optional, default: (0, 0)
Center position of the chart. Takes value (0, 0) or is a sequence
of 2 scalars.
# center: 列表或者浮点数默认为(0,0)
# 图的中心位置设置的位置
frame : bool, optional, default: False
Plot axes frame with the chart if true.
# frame:布尔类型
rotatelabels : bool, optional, default: False
Rotate each label to the angle of the corresponding slice if true.
# ritatelabels:布尔
# 旋转为真时旋转标签相应的角度
看到一个大佬写的,真的写的太详细了,真不错,大家直接移步吧。
matplotlib 知识点11:绘制饼图(pie 函数精讲)
接下来我上一个大作业给大家看一下结合所有所学过的知识,如何画一个好看点的饼图把。
注意:以下代码不可复制直接使用
"""
2020年2月23日
将成都二手房数据根据不同价格找出相应的个数,然后将不同价格区间的房子数量做成饼图
"""
import matplotlib.pyplot as plt
import pandas as pd
file_path = '..\\doc\\processed_data\\cd_lianjia-v3_ed_nodump.csv'
to_path = "..\\doc\\pic\\成都二手房总价占比饼图.png"
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文
plt.rcParams['axes.unicode_minus'] = False # 显示负号
# 导入去重后的结果
df = pd.read_csv(file_path)
# 找出总价在0~100万区间的房子的dataframe
df_0_100 = df[(df['总价'] >= 0) & (df['总价'] <= 100)]
# 抓出总价列表,计算长度就是房子总价在0~100的个数
num_of_0_100 = len(df_0_100['总价'])
df_100_150 = df[(df['总价'] > 100) & (df['总价'] <= 150)]
num_of_100_150 = len(df_100_150['总价'])
df_150_200 = df[(df['总价'] > 150) & (df['总价'] <= 200)]
num_of_150_200 = len(df_150_200['总价'])
df_200_250 = df[(df['总价'] > 200) & (df['总价'] <= 250)]
num_of_200_250 = len(df_200_250['总价'])
df_250_300 = df[(df['总价'] > 250) & (df['总价'] <= 300)]
num_of_250_300 = len(df_250_300['总价'])
df_300_above = df[df['总价'] > 300]
num_of_30_above = len(df_300_above['总价'])
# 房子总数
total_num = len(df['总价'])
# 开始拼装数据
data = [num_of_0_100 / total_num, num_of_100_150 / total_num, num_of_150_200 / total_num, num_of_200_250 / total_num,
num_of_250_300 / total_num, num_of_30_above / total_num]
labels = ['0~100万', '100~150万', '150~200万', '200~250万', '250~300万', '300万及以上']
explode = (0.05, 0.05, 0, 0, 0, 0)
plt.figure(figsize=(20, 8), dpi=80)
plt.pie(data, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
plt.title("2020年2月成都市二手房不同价格区间及其所占比例")
plt.savefig(to_path)
效果图:
总结
那么这段详解matplotlib也算是结束了,这段时间通过翻源码、查文档,我彻彻底底的搞清楚了matplotlib的尿性,也熟练了折线图、直方图、柱状图、饼图的使用。同时也配合自己采集的数据练习了pandas,也是一举多得。通过这种写博客的方式,将自己一无所知的对象彻底搞懂,然后通过白话的方式再复述出来,配合文档的理解,确实是对自己提升的好方法。