2017-04-24 4 views
3

가 나는 다음과 같은 그림을 x 값에 대한 전설을 추가하기 위해 노력하고있어 sns.countplot()시본 countplot 설정 전설

하여 범주 형 데이터 값 수를 ploting있어 값 , labels은 x 값의 설명입니다.

전설 'VP'인스턴스를 지원하지 않습니다

ax = sns.countplot(x = df.GARAGE_DOM) 
handles, labels = ax.get_legend_handles_labels() 

handles = ["VP", "BC", "GC", "GP", "JC", "PO"] 
labels = ["Voie Publique", "box", "Garage couvert", "garage particulier clos", "Jardin clos", "parking ouvert"] 
by_label = OrderedDict(zip(handles,labels)) 
ax.legend(by_label.keys(), by_label.values()) 

그러나, 나는

이 UserWarning 것을 경고 얻었다. 대신 프록시 아티스트를 사용할 수 있습니다. 참조는 : http://matplotlib.org/users/legend_guide.html#using-proxy-artist

나는 프록시 작가의 문서를 읽은하지만 내 경우에는 예를 찾을 수 없습니다. 당신의 도움에 대한

enter image description here

감사합니다.

답변

2

가능한 해결책은 텍스트 필드를 범례 처리기로 만드는 것입니다. 다음은 간단한 matplotlib.text.Text 인스턴스 인 범례 아티스트를 만드는 데 사용되는 TextHandler을 만듭니다. 범례의 핸들은 TextHandler이 원하는 Text을 생성하는 (텍스트, 색상)의 튜플로 제공됩니다.

import seaborn as sns 
import matplotlib.pyplot as plt 
from matplotlib.legend_handler import HandlerBase 
from matplotlib.text import Text 
import numpy as np 
import pandas as pd 

class TextHandler(HandlerBase): 
    def create_artists(self, legend, tup ,xdescent, ydescent, 
         width, height, fontsize,trans): 
     tx = Text(width/2.,height/2,tup[0], fontsize=fontsize, 
        ha="center", va="center", color=tup[1], fontweight="bold") 
     return [tx] 


a = np.random.choice(["VP", "BC", "GC", "GP", "JC", "PO"], size=100, 
        p=np.arange(1,7)/21.) 
df = pd.DataFrame(a, columns=["GARAGE_DOM"]) 

ax = sns.countplot(x = df.GARAGE_DOM) 


handltext = ["VP", "BC", "GC", "GP", "JC", "PO"] 
labels = ["Voie Publique", "box", "Garage couvert", "garage particulier clos", "Jardin clos", "parking ouvert"] 


t = ax.get_xticklabels() 
labeldic = dict(zip(handltext, labels)) 
labels = [labeldic[h.get_text()] for h in t] 
handles = [(h.get_text(),c.get_fc()) for h,c in zip(t,ax.patches)] 

ax.legend(handles, labels, handler_map={tuple : TextHandler()}) 

plt.show() 

enter image description here


상기 용액

더 복잡한 것 아래 일본어 버전의 업데이트 된 버전이다. 다음은 원래 솔루션으로 TextAreaAnchoredOffsetbox을 사용하여 범례 안에 텍스트를 배치합니다.

import seaborn.apionly as sns 
import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
from matplotlib.offsetbox import TextArea, AnchoredOffsetbox 
from matplotlib.transforms import TransformedBbox, Bbox 
from matplotlib.legend_handler import HandlerBase 
import numpy as np 
import pandas as pd 

class TextHandler(HandlerBase): 
    def __init__(self, text, color="k"): 
     self.text = text 
     self.color = color 
     super(TextHandler, self).__init__() 

    def create_artists(self, legend, orig_handle,xdescent, ydescent, 
         width, height, fontsize,trans): 
     bb = Bbox.from_bounds(xdescent,ydescent, width,height) 
     tbb = TransformedBbox(bb, trans) 
     textbox = TextArea(self.text, textprops={"weight":"bold","color":self.color}) 
     ab = AnchoredOffsetbox(loc=10,child=textbox, bbox_to_anchor=tbb, frameon=False) 
     return [ab] 


a = np.random.choice(["VP", "BC", "GC", "GP", "JC", "PO"], size=100, 
        p=np.arange(1,7)/21.) 
df = pd.DataFrame(a, columns=["GARAGE_DOM"]) 

ax = sns.countplot(x = df.GARAGE_DOM) 


handltext = ["VP", "BC", "GC", "GP", "JC", "PO"] 
labels = ["Voie Publique", "box", "Garage couvert", "garage particulier clos", "Jardin clos", "parking ouvert"] 

handles = [ patches.Rectangle((0,0),1,1) for h in handltext] 
t = ax.get_xticklabels() 
labeldic = dict(zip(handltext, labels)) 
labels = [labeldic[h.get_text()] for h in t] 
handlers = [TextHandler(h.get_text(),c.get_fc()) for h,c in zip(t,ax.patches)] 
handlermap = dict(zip(handles, handlers)) 
ax.legend(handles, labels, handler_map=handlermap,) 

plt.show() 
+0

텍스트 필드 트릭을 가져 주셔서 감사합니다. 아주 잘 작동합니다. – Cheng