問題
在分析數(shù)據(jù)的過程中,通常要對數(shù)據(jù)進行可視化召烂,為了表示某一屬性數(shù)據(jù)的分布碱工,可以為數(shù)據(jù)畫餅圖:
import pandas as pd
import matplotlib.pyplot as plt
# 導(dǎo)入數(shù)據(jù) df
plt.pie(df['value'].value_counts(), labels=['label_1','label_2'], autopct='%1.1f%%');
這里通過參數(shù)labels
指定餅圖上各部分的標簽。這就引入了一個問題奏夫,怎么才能保證每個標簽正確的對應(yīng)到相應(yīng)的部分呢怕篷?
分析
- 首先看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.
并沒有關(guān)于順序的說明。僅僅提到酗昼,默認情況下廊谓,各部分是按照逆時針方向排列。
- 接下來考慮
df['value'].value_counts()
的順序
通過多次實驗麻削,發(fā)現(xiàn)餅圖的各部分其實是按照df['value'].value_counts()
中數(shù)值的順序逆時針排列的蹂析。 - 查看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
碟婆,其中的數(shù)值是降序排列的,也就是說第一個元素是出現(xiàn)頻度最高的對象惕稻。
結(jié)論
餅圖各部分的順序是由第一個array-like
的參數(shù)中數(shù)值的順序決定的竖共。在某些情況下,array-like
的參數(shù)是以df['value'].value_counts()
的形式提供俺祠,而df['value'].value_counts()
內(nèi)元素的順序是降序排列的公给。所以說借帘,在繪制餅圖之前,要先查看value_counts()
中元素的順序淌铐,然后根據(jù)具體的情況為其指定labels
肺然。
plt.pie(df['value'].value_counts(), labels=['label_1','label_2'], autopct='%1.1f%%');