꺼내먹는지식 준

Matplotlib Text Visualization 본문

CS/데이터시각화

Matplotlib Text Visualization

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

Visual representation이 줄 수 없는 여러 설명들을 text가 추가 설명 

잘못된 전달에서 생기는 오해를 방지 

 

1) Title: 가장 큰 주제 (전체 figure, subplot figure, 위치)

2) Label: 축에 해당하는 데이터 정보 제공 (x축, y축을 설명하는 정보, 축과는 다른 정보)

3) Tick Label: 축에 눈금을 사용하여 스케일 정보를 추가 (큰 축, 작은 축 라벨 메이저 마이너 .. )

4) Legend: 한 그래프에서 두가지 이상의 데이터를 분류하기 위해 보조적인 정보를 차트내에서 전달

5) Annotation(Text): 그 외의 시각화에 대한 설명을 추가 (거의 유사 Annotation은 화살표 추가 가능)

 

fig, ax = plt.subplots()

fig.suptitle('Figure Title')

ax.plot([1, 3, 2], label='legend')
ax.legend()

ax.set_title('Ax Title')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')

ax.text(x=1,y=2, s='Text')
fig.text(0.5, 0.6, s='Figure Text')

plt.show()

subplots() default nrow = 1 ncolumn = 1

아마 fig.text는 모든 figure에 달릴 것으로 보인다. 

 

 

ax.text로 원하는 위치에 글 달기 가능 

fig.text 도 가능 

 

Text Properties 

Font

family: 글씨체 

style: italic, normalm

variant: 잘 사용 X

weight: 글씨 두께, 숫자도 사용 가능 (light ~ bold)

가독성 관련 글 : 

size: 크기 

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

ax.text(x=0.5, y=0.5, s='Text\nis Important',
         fontsize=20,
         fontweight='bold',
         fontfamily='serif',
       )


plt.show()

 

Details 

 

color: 색상 

linespacing: 줄과 줄 간의 간격 

background: 배경색 

alpha: 투명도 

zorder: 앞 뒤 순서

visible: False 보이지 않도록

 

 

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

ax.text(x=0.5, y=0.5, s='Text\nis Important',
        fontsize=20,
        fontweight='bold',
        fontfamily='serif',
         color='royalblue',
         linespacing=2,
         backgroundcolor='lightgray',
         alpha=0.5
       )


plt.show()

굉장히 직관적

 

Alignment

 

ha: horizontal alignment 

va: vertical alignment 

rotation: (= hori zontal, vertical, degree )

multialignment

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

ax.text(x=0.5, y=0.5, s='Text\nis Important',
        fontsize=20,
        fontweight='bold',
        fontfamily='serif',
        color='royalblue',
        linespacing=2,
        va='center', # top, bottom, center
        ha='center', # left, right, center
        rotation='vertical'  #horizontal?
       )


plt.show()

Bbox 

시각화를 하다보면 box 가 필요한 경우가 발생한다. 

 

bbox = dict(boxstyle = 'round', facecolor = 'wheat', ec= 'blue' #(edge color), alpha = 0.4, pad = 1 #(edge와의 거리 차))

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

ax.text(x=0.5, y=0.5, s='Text\nis Important',
        fontsize=20,
        fontweight='bold',
        fontfamily='serif',
        color='black',
        linespacing=2,
        va='center', # top, bottom, center
        ha='center', # left, right, center
        rotation='horizontal', # vertical?
        bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.4)
       )


plt.show()

bbox = dict(boxstyle = 'round', facecolor = 'wheat', alpha = 0.4)

 

 

문법 활용 실습 

 

fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111, aspect=1)

for g, c in zip(['male', 'female'], ['royalblue', 'tomato']):
    student_sub = student[student['gender']==g]
    ax.scatter(x=student_sub ['math score'], y=student_sub ['reading score'],
               c=c,
               alpha=0.5, 
               label=g)
    
ax.set_xlim(-3, 102)
ax.set_ylim(-3, 102)

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

ax.set_xlabel('Math Score', 
              fontweight='semibold')
ax.set_ylabel('Reading Score', 
              fontweight='semibold')

ax.set_title('Score Relation', 
             loc='left', va='bottom',
             fontweight='bold', fontsize=15
            )

ax.legend(
    title='Gender',
    shadow=True,
    labelspacing=1.2,
#     loc='lower right'
#     bbox_to_anchor=[1.2, 0.5]
)

plt.show()

zip 

g,c = (male, royablue)

g,c = (female, tomato)

 

student['gender'] == g 인 경우에만, c = c 로 하여서 scatter하여라. 

 

별다르게 어려운 건 없다.

 

def score_band(x):
    tmp = (x+9)//10
    if tmp <= 1: 
        return '0 - 10'
    return f'{tmp*10-9} - {tmp*10}'

student['math-range'] = student['math score'].apply(score_band)
student['math-range'].value_counts().sort_index()

math_grade = student['math-range'].value_counts().sort_index()

fig, ax = plt.subplots(1, 1, figsize=(11, 7))
ax.bar(math_grade.index, math_grade,
       width=0.65, 
       color='royalblue',
       linewidth=1,
       edgecolor='black'
      )

ax.margins(0.01, 0.1)
ax.set(frame_on=False)
ax.set_yticks([])
ax.set_xticks(np.arange(len(math_grade)))
ax.set_xticklabels(math_grade.index)

ax.set_title('Math Score Distribution', fontsize=14, fontweight='semibold')

for idx, val in math_grade.iteritems():
    ax.text(x=idx, y=val+3, s=val,
            va='bottom', ha='center',
            fontsize=11, fontweight='semibold'
           )

plt.show()

 

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

Seaborn 이란?  (0) 2022.02.12
Matplotlib Facet (figure 위치 바꾸기)  (0) 2022.02.12
Matplotlib Color  (0) 2022.02.07
Matplotlib 기본기에서 벗어나는 몇가지 팁  (0) 2022.02.07
Matplotlib Scatter Plot  (0) 2022.02.04
Comments