2017-01-05 15 views
7

판다 데이터 프레임의 열 항목으로 matplotlib에서 만든 scatter/bubble 차트에 레이블을 지정하려고합니다. 많은 예제와 질문을 보았습니다 (예 : herehere 참조). 그래서 그에 따라 플롯에 주석을 달았습니다. pandas 데이터 프레임의 열로 거품 형 차트/산점도에 라벨을 지정하는 방법은 무엇입니까?

import matplotlib.pyplot as plt 
import pandas as pd 
#example data frame 
x = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30] 
y = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600] 
s = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30] 
users =['mark', 'mark', 'mark', 'rachel', 'rachel', 'rachel', 'jeff', 'jeff', 'jeff', 'lauren', 'lauren', 'lauren'] 

df = pd.DataFrame(dict(x=x, y=y, users=users) 

#my attempt to plot things 
plt.scatter(x_axis, y_axis, s=area, alpha=0.5) 
    plt.xlabel(xlabel) 
    plt.ylabel(ylabel) 
    plt.annotate(df.users, xy=(x,y)) 
    plt.show() 

가 나는 팬더 datframe를 사용하고 어떻게 든 그래서 나는 dict() 객체가 예상되는 추측 KeyError-를 얻을 : 여기에 내가 무엇입니까? 팬더 데이터 프레임의 항목을 사용하여 데이터에 레이블을 지정하는 다른 방법이 있습니까?

답변

6

당신은 DataFrame.plot.scatter을 사용하고 DataFrame.iat에 의해 루프에서 선택할 수 있습니다

ax = df.plot.scatter(x='x', y='y', alpha=0.5) 
for i, txt in enumerate(df.users): 
    ax.annotate(txt, (df.x.iat[i],df.y.iat[i])) 
plt.show() 

graph

+0

감사합니다! 이것은 굉장합니다! bubblechart로 변환하는 방법이 있습니까? 나는'ax = df.plot.scatter (x = 'x', y = 'y', s = 's', alpha = 0.5)'시도했지만'TypeError'를 얻는다. 어떤 아이디어? – Rachel

+1

당신은'ax = df.plot.scatter (x = 'x', y = 'y', s = s, 알파 = 0.5) 만 필요합니다''s = 's ''를's = s' 입력은 목록이 아닌 열 – jezrael

+0

고마워요! 이것은 꽤 오랜 시간을 절약 해주었습니다! – Rachel

1

Jezreal의 대답은 괜찮지 만, 나는이 그냥 내가 다른 스레드에서 df.iterrows으로 무엇을 의미하는지 보여 게시 할 예정입니다 .

동적 크기를 원할 경우 루프에 scatter (또는 plot) 명령을 넣어야합니다.

df = pd.DataFrame(dict(x=x, y=y, s=s, users=users)) 

fig, ax = plt.subplots(facecolor='w') 

for key, row in df.iterrows(): 
    ax.scatter(row['x'], row['y'], s=row['s']*5, alpha=.5) 
    ax.annotate(row['users'], xy=(row['x'], row['y'])) 

enter image description here

+0

감사합니다. 훌륭한 답변입니다. 플러스 : 그것은 그림, 도끼 = plt.subplots (facecolor = 'w')'를 통해 줄거리의 모양과 conivienently 수 있습니다! – Rachel