2013-03-14 45 views
2

我有一個熊貓數據幀:如何擺脫額外的熊貓情節()的圖例條目?

>>> drawdata 
        sales  mg 
ID  RPT_Date     
600809 20120331 22.1401 13.5591 
     20120630 38.1565 22.8968 
     20120930 52.5098 31.5909 

及以下命令繪製柱狀圖如下IMG:

>>> drawdata.unstack('ID').plot(kind='bar', use_index=True) 
<matplotlib.axes.AxesSubplot object at 0x035A9D70> 

enter image description here

我的問題顯示爲註釋:如何獲得擺脫額外的傳奇入口?

(此URL相關: How to barplot Pandas dataframe columns aligning by sub-index?

編輯:(對於HYRY方法的更多信息)


# -*- coding: utf-8 -*- 

import itertools 
import pandas as pd 
import io 

text = '''\ 
ID RPT_Date sales mg 
000568 20120331 22.140 13.559 
000568 20120630 38.156 22.896 
000568 20120930 52.509 31.590 
''' 

drawdata = pd.read_csv(io.BytesIO(text), delimiter = ' ', converters = {0:str}) 
drawdata.set_index(['ID','RPT_Date'], inplace = True) 

ax = drawdata.unstack('ID').plot(kind='bar', use_index=True, legend=False) 

display_acct_list = list(drawdata.columns) 
legend_list = list(itertools.product(display_acct_list, list(set(drawdata.index.get_level_values('ID'))))) 
legend_list = [x[0] + '-' + x[1] for x in legend_list] 

ax.legend(legend_list, loc='best', fancybox=True, shadow=True) 

ax.set_xlabel("") 

圖表中缺少圖例中的 「顏色盒」。

enter image description here

回答

3

您可以通過關閉圖例標題:

drawdata.unstack('ID').plot().get_legend().set_title("") 

或者,您可以自己繪製的傳說:

import pylab as pl 
drawdata.unstack('ID').plot(legend=False) 
pl.legend(loc="best") 

對於你的第二個問題:

那是因爲劇情中有一條虛線,如果你縮小一點,你會看到它。設置圖例標籤時,第一個標籤將顯示在虛線上。您可以通過以下行修復:

ax.legend(ax.containers, legend_list, loc='best', fancybox=True, shadow=True) 
+0

感謝您的代碼。有用。但是,因爲我需要自定義圖例文本並將軸對象分配給變量以便稍後進行處理,所以我使用第二種方法。現在我遇到了另一個問題:傳奇內的第一個「彩盒」丟失了!我將整個代碼和圖表附加到更新區域中。你可以看一下嗎? – bigbug 2013-03-16 13:46:51

+0

好的,修復它,請再次檢查答案。 – HYRY 2013-03-16 14:23:49

+0

太棒了!解決我最頭痛的問題之一。非常感謝。 – bigbug 2013-03-17 01:35:30