꺼내먹는지식 준

Matplotlib Color 본문

CS/데이터시각화

Matplotlib Color

알 수 없는 사용자 2022. 2. 7. 15:33

위치와 은 가장 효과적인 채널 구분 

위치는 시각화 방법에 따라 결정, 

색은 직접 골라야 한다. 

색이 가자고 있는 의미는 각각 다르다.  (기업, 정당 색상, 온도, 등)좋은 색과 색 배치는 시각적으로 훌룡하다. 가장 중요한 것은 인사이트 전달이다.

 

Color Palette

범주형(Discrete, Qualitative):

독립된 데이터를 표현하기 위한 독립된 색상

최대 10가지 색상

색의 차이로 구분하는 것이 특징 (채도 명도를 개별적 조정은 지양)

 

# Group to Number
groups = sorted(student['race/ethnicity'].unique())
gton = dict(zip(groups , range(5)))

# Group에 따라 색 0, 1, 2, 3, 4
student['color'] = student['race/ethnicity'].map(gton)

색상별로 index 1,2,3,4,5 지정 

from matplotlib.colors import ListedColormap

qualitative_cm_list = ['Pastel1', 'Pastel2', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10']

fig, axes = plt.subplots(2, 4, figsize=(20, 8))
axes = axes.flatten()

student_sub = student.sample(100)

for idx, cm in enumerate(qualitative_cm_list):    
    pcm = axes[idx].scatter(student_sub['math score'], student_sub['reading score'],
                     c=student_sub['color'], cmap=ListedColormap(plt.cm.get_cmap(cm).colors[:5])
                     )
    cbar = fig.colorbar(pcm, ax=axes[idx], ticks=range(5))
    cbar.ax.set_yticklabels(groups)
    axes[idx].set_title(cm)
    
plt.show()

axes.flatten() 

접근시 용이하다. axes[][] -> axes[idx]

c는 홀로쓰이면 color 값, 같이 쓰이면 다음과 같이 된다. 

c = [점 개수만 큼], cmap = color 팔렛트중 원하는 색상 

c = [0, 1,2,3,4,1,2,0 ,3,4,1,2,3,4,0..]  

cmap 은 팔렛트 [:5] 그 중 5개만 가져온다. 

작을 수록, 지정 된 cmap 에서 작은 값, 

클 수록,  지정 된 cmap에서 큰 값을 가져온다. 

 

 

 

연속형(Sequential)

정렬된 값을 가지는 순서형, 연속형 변수에 적합 

연속적인 색상을 사용하여 값을 표현 : 어두운 배경에서는 밝은 색, 밝은 배경에서는 어두운 색이 큰 값을 표현 

색상은 단일 색조로 표현, 균일한 색상 변화 중요 

sequential_cm_list = ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
            'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
            'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']

fig, axes = plt.subplots(3, 6, figsize=(25, 10))
axes = axes.flatten()

student_sub = student.sample(100)

for idx, cm in enumerate(sequential_cm_list):    
    pcm = axes[idx].scatter(student['math score'], student['reading score'],
                            c= student['reading score'], 
                            cmap=cm,
                            vmin=0, vmax=100
                    
                     )
    fig.colorbar(pcm, ax=axes[idx])
    axes[idx].set_title(cm)
    
plt.show()

OrRd: Orange to Red 

 

vmin, vmax 값에 따라  y값이 0 ~ 100 으로 수정된 것을 볼 수 있다. 

 

위에서 설명한 것과 같이, 값이 작을 수록 ~ 클 수록 cmap의 색상에 맵핑 된다. 

 

im =  np.random.randint(10, size=(7, 52))
fig, ax = plt.subplots(figsize=(20, 5))
ax.imshow(im, cmap='Greens')
ax.set_yticks(np.arange(7)+0.5, minor=True)
ax.set_xticks(np.arange(52)+0.5, minor=True)
ax.grid(which='minor', color="w", linestyle='-', linewidth=3)
plt.show()

위 사진의 github record. 

 

발산형(Diverge)

연속형과 유사하나, 중앙을 기준으로 발산

상반된 값 (ex.기온)

서로 다른 2개(ex.지지율) 을 표현하는 데 적합

양 끝으로 갈 수록 색이 진해지며, 중앙의 색은 양쪽의 점에서 편향되지 않아야 한다. 

 

from matplotlib.colors import TwoSlopeNorm

diverging_cm_list = ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']

fig, axes = plt.subplots(3, 4, figsize=(20, 15))
axes = axes.flatten()

offset = TwoSlopeNorm(vmin=0, vcenter=student['reading score'].mean(), vmax=100)

student_sub = student.sample(100)

for idx, cm in enumerate(diverging_cm_list):    
    pcm = axes[idx].scatter(student['math score'], student['reading score'],
                            c=offset(student['math score']), 
                            cmap=cm,
                     )
    cbar = fig.colorbar(pcm, ax=axes[idx], 
                        ticks=[0, 0.5, 1], 
                        orientation='horizontal'
                       )
    cbar.ax.set_xticklabels([0, student['math score'].mean(), 100])
    axes[idx].set_title(cm)
    
plt.show()

 

강조 대비 

데이터에서 다름을 보이기 위한 Highlight

 

강조를 위한 색상 대비 

명도 대비 : 밝은색 vs 어두운 색 --> 밝은 색은 더 밝게, 어두운 색은 더 어둡게 보이게 함 (회색 검정)

 

a_color, nota_color = 'black', 'lightgray'

colors = student['race/ethnicity'].apply(lambda x : a_color if x =='group A' else nota_color)
color_bars = [a_color] + [nota_color]*4

fig = plt.figure(figsize=(18, 15))
groups = student['race/ethnicity'].value_counts().sort_index()

ax_bar = fig.add_subplot(2, 1, 1)
ax_bar.bar(groups.index, groups, color=color_bars, width=0.5)

ax_s1 = fig.add_subplot(2, 3, 4)
ax_s2 = fig.add_subplot(2, 3, 5)
ax_s3 = fig.add_subplot(2, 3, 6)

ax_s1.scatter(student['math score'], student['reading score'], color=colors, alpha=0.5)
ax_s2.scatter(student['math score'], student['writing score'], color=colors, alpha=0.5)
ax_s3.scatter(student['writing score'], student['reading score'], color=colors, alpha=0.5)

for ax in [ax_s1, ax_s2, ax_s3]:
    ax.set_xlim(-2, 105)
    ax.set_ylim(-2, 105)

plt.show()

light_gray와 대비대는 색상 

색상 대비 : 가까운 색은 차이가 더 크게 보임 (파랑보라, 빨강보라)

a_color, nota_color = 'orange', 'lightgray'

colors = student['race/ethnicity'].apply(lambda x : a_color if x =='group A' else nota_color)
color_bars = [a_color] + [nota_color]*4

fig = plt.figure(figsize=(18, 15))
groups = student['race/ethnicity'].value_counts().sort_index()

ax_bar = fig.add_subplot(2, 1, 1)
ax_bar.bar(groups.index, groups, color=color_bars, width=0.5)

ax_s1 = fig.add_subplot(2, 3, 4)
ax_s2 = fig.add_subplot(2, 3, 5)
ax_s3 = fig.add_subplot(2, 3, 6)

ax_s1.scatter(student['math score'], student['reading score'], color=colors, alpha=0.3)
ax_s2.scatter(student['math score'], student['writing score'], color=colors, alpha=0.3)
ax_s3.scatter(student['writing score'], student['reading score'], color=colors, alpha=0.3)

for ax in [ax_s1, ax_s2, ax_s3]:
    ax.set_xlim(-2, 105)
    ax.set_ylim(-2, 105)

plt.show()

채도 대비 : 채도의 차이, 채도가 더 높아보임 (회색 주황)

보색 대비 : 정반대 색상을 사용하면 더 선명해 보인다 (빨강 초록)

 

 

 

색각 이상 

삼원색 중에 특정 색을 감지 못하면 색맹 

부분적 인지 이상이 있다면 색약 

색 인지가 중요한 분야에 있어서는 이에 대한 고려가 필수 (과학/ 연구)

 

 

 

색상을 표현할 때 r,g,b 보다는 h,s,l (색조 채도 광도)를 이해하는 것이 중요하다. 

색조: 빨, 파, 초 등 색상으로 생각하는 부분 

채도: (채도가 낮다 회색에 가깝다. 채도가 높다 쨍한 색상)

광도: (색이 연하다, 색이 진하다.)

 

'CS > 데이터시각화' 카테고리의 다른 글

Matplotlib Facet (figure 위치 바꾸기)  (0) 2022.02.12
Matplotlib Text Visualization  (0) 2022.02.07
Matplotlib 기본기에서 벗어나는 몇가지 팁  (0) 2022.02.07
Matplotlib Scatter Plot  (0) 2022.02.04
Matplotlib Line Plot  (0) 2022.02.03
Comments