问题
在分析数据的过程中,通常要对数据进行可视化,为了表示某一属性数据的分布,可以为数据画饼图:
import pandas as pd
import matplotlib.pyplot as plt
# 导入数据 df
plt.pie(df['value'].value_counts(), labels=['label_1','label_2'], autopct='%1.1f%%');
这里通过参数labels
指定饼图上各部分的标签。这就引入了一个问题,怎么才能保证每个标签正确的对应到相应的部分呢?
分析
- 首先看matplotlib.pyplot.pie的API定义:
Make a pie chart of array x. The fractional area of each wedge is given by x/sum(x). If sum(x) < 1, then the values of x give the fractional area directly and the array will not be normalized. The resulting pie will have an empty wedge of size 1 - sum(x).
The wedges are plotted counterclockwise, by default starting from the x-axis.
并没有关于顺序的说明。仅仅提到,默认情况下,各部分是按照逆时针方向排列。
- 接下来考虑
df['value'].value_counts()
的顺序
通过多次实验,发现饼图的各部分其实是按照df['value'].value_counts()
中数值的顺序逆时针排列的。 - 查看value_counts()的定义
Return a Series containing counts of unique values.
The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.
可以看到,value_counts()
返回的是一个Series
,其中的数值是降序排列的,也就是说第一个元素是出现频度最高的对象。
结论
饼图各部分的顺序是由第一个array-like
的参数中数值的顺序决定的。在某些情况下,array-like
的参数是以df['value'].value_counts()
的形式提供,而df['value'].value_counts()
内元素的顺序是降序排列的。所以说,在绘制饼图之前,要先查看value_counts()
中元素的顺序,然后根据具体的情况为其指定labels
。
plt.pie(df['value'].value_counts(), labels=['label_1','label_2'], autopct='%1.1f%%');
网友评论