2016-02-18 51 views
4

我已經生成了一個餅圖,使用熊貓包裝counts.plot(kind='pie')和Matplotlib直`plt.pie(計數)。Matplotlib,Pandas,Pie Chart標籤錯誤

問題在於標籤。同時使用餅圖可以正確表示值=餅圖楔,但是當我開始引入自定義顏色和圖例時,標籤會關閉。

enter image description here

餅圖標籤是正確的,但傳說標籤相對於繪製他們的標籤順序group_name,而不是它們的值。有想法該怎麼解決這個嗎?

代碼=

group_names = ['2-3 km', '3-5 km','5-7 km','7-10 km','10-20 km','20-50 km','50-75 km','75-100 km','>100 km'] 

df['bins'] = pd.cut(df['distkm'], bins) 
df['categories'] = pd.cut(df['distkm'], bins, labels=group_names) 

counts = df['categories'].value_counts() 
plt.axis('equal') 
explode = (0, 0, 0,0.1,0.1,0.2,0.3,0.4,0.6) 
colors = ['#191970','#001CF0','#0038E2','#0055D4','#0071C6','#008DB8','#00AAAA','#00C69C','#00E28E','#00FF80',] 
counts.plot(kind='pie', fontsize=17,colors=colors,explode=explode) 
plt.legend(labels=group_names,loc="best") 

plt.show() 

數據看起來像

20-50 km  1109 
50-75 km  696 
10-20 km  353 
75-100 km  192 
3-5 km  168 
7-10 km  86 
5-7 km   74 
>100 km  65 
2-3 km   53 
dtype: int64 

回答

8

group_names不在相同的順序counts.index。因此,而不是使用

plt.legend(labels=group_names,loc="best") 

使用

plt.legend(labels=counts.index, loc="best") 

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 

group_names = ['2-3 km', '3-5 km', '5-7 km', '7-10 km', '10-20 km', '20-50 km', 
       '50-75 km', '75-100 km', '>100 km'] 

counts = pd.Series([1109, 696, 353, 192, 168, 86, 74, 65, 53], 
        index=['20-50 km', '50-75 km', '10-20 km', '75-100 km', 
          '3-5 km', '7-10 km', '5-7 km', '>100 km', '2-3 km']) 

explode = (0, 0, 0, 0.1, 0.1, 0.2, 0.3, 0.4, 0.6) 
colors = ['#191970', '#001CF0', '#0038E2', '#0055D4', '#0071C6', '#008DB8', '#00AAAA', 
      '#00C69C', '#00E28E', '#00FF80', ] 

counts.plot(kind='pie', fontsize=17, colors=colors, explode=explode) 
plt.axis('equal') 
plt.ylabel('') 
plt.legend(labels=counts.index, loc="best") 
plt.show() 

enter image description here

0

您可以在熊貓據幀轉換到一個列表和情節與matplotlib直接:

sizes = counts.values.tolist() 
plt.axis('equal') 
plt.pie(sizes,explode=explode,labels=group_names,colors=colors) 
plt.legend(labels=group_names,loc="best") 
plt.show() 
1

創建值計數,如果我取消自動排序,圖例繪製正確。

counts = df['categories'].value_counts(sort=False)enter image description here