2017-01-04 14 views
1

약 9800 개의 항목이있는 데이터 세트가 있습니다. 하나의 열은 사용자 이름 (약 60 개의 개별 사용자 이름)을 포함합니다. matplotlib에 산점도를 만들고 다른 사용자에게 다른 색상을 지정하고 싶습니다.matplotlib을 사용하여 색상을 자동으로 할당합니다.

import matplotlib.pyplot as plt 
import pandas as pd 

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] 
users =['mark', 'mark', 'mark', 'rachel', 'rachel', 'rachel', 'jeff', 'jeff', 'jeff', 'lauren', 'lauren', 'lauren'] 

#this is how the dataframe basicaly looks like  
df = pd.DataFrame(dict(x=x, y=y, users=users) 

#I go on an append the df with colors manually 
#I'll just do it the easy albeit slow way here 

colors =['red', 'red', 'red', 'green', 'green', 'green', 'blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow'] 

#this is the dataframe I use for plotting 
df1 = pd.DataFrame(dict(x=x, y=y, users=users, colors=colors) 

plt.scatter(df1.x, df1.y, c=df1.colors, alpha=0.5) 
plt.show() 

는 그러나, 나는 수동으로 사용자에게 색상을 지정하지 않으 :

이것은 내가 무엇을 기본적으로. 앞으로 몇 주 안에이 작업을 여러 번해야하며 사용자는 매번 다를 것입니다.

나는 두 가지 질문이 있습니다

(1) 개별 사용자에게 자동으로 색상을 지정하는 방법이 있나요? (2) 그렇다면 색 구성표 또는 팔레트를 할당하는 방법이 있습니까?

+0

가능한 복제 [팬더/Pyplot에서 분산 형 플롯 : 카테고리 별 플롯하는 방법 (http://stackoverflow.com/ 질문/21654635/분산 형 플롯 - 판다 - 파이롯트 - 방법별 - 플로트 별) – tom

+0

@tom 그렇게 생각하지 않습니다. 데이터 프레임에 색상 열을 동적으로 할당하는 방법이 필요합니다. 당신이 제안한 질문은 색이 아닌 그룹화 된 그림과 관련이 있습니다. – Rachel

답변

2
user_colors = {} 
unique_users = list(set(users)) 
step_size = (256**3) // len(unique_users) 
for i, user in enumerate(unique_users): 
    user_colors[user] = '#{}'.format(hex(step_size * i)[2:]) 

그런 다음 각 사용자마다 고유 한 색상이있는 사전 (user_colors)이 있습니다.

colors = [user_colors[user] for user in users] 

는 이제 각 사용자에 대해 고유 한 색상 배열을 가지고

+0

고마워요! 네가하는 일을 이해할 것 같아. 그러나 팬더 데이터 프레임에도 적용 할 수 있습니까? 어떻게 작동할까요? – Rachel