1 분 소요

Matplotlib 에서 text

text로 그림으로서 전달할 수 없는 설명 추가하거나 잘못된 전달에서 생기는 오해를 방지할 수 있다.

Anatomy of a figure

  • Title : 가장 큰 주제를 설명
  • Label : 축에 해당하는 데이터 정보를 제공
  • Tick label : 축에 눈금을 사용하여 스케일 정보를 추가
  • Legend : 한 그래프에서 2개 이상의 서로 다른 데이터 분류 위해 사용
  • Annotation, Text : 그 외의 시각화에 대한 설명 추가

코-드

2.1 Font

폰트 요소

  • family
  • size or fontsize
  • style or fontstyle
  • weight or fontweight

image-20221009122356109

2.2 Details

커스텀할 수 있는 요소들

  • color
  • linespacing
  • backgroundcolor
  • alpha
  • zorder
  • visible

2.3 Alignment

정렬 관련 요소들

  • ha : horizontal alignment
  • va : vertical alignment
  • rotation
  • multialignment

2.4 bbox

image-20221009123151683

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',ec='blue', alpha=0.4)
       )


plt.show()

image-20221009123256023

3.1 Title & Legend

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]
)

image-20221009124039302

link : 더 자세한 사항

3.2 Ticks & Text

ticks: 축에 data point 나타내는 마커

막대 위에 text로 표시하는 코-드

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([]) # y ticks 없애주기
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()

image-20221009130214758

annotate

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

i = 13

ax.scatter(x=student['math score'], y=student['reading score'],
           c='lightgray',
           alpha=0.9, zorder=5)
    
ax.scatter(x=student['math score'][i], y=student['reading score'][i],
           c='tomato',
           alpha=1, zorder=10)    
    
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')
ax.set_ylabel('Reading Score')

ax.set_title('Score Relation')

# x축과 평행한 선
ax.plot([-3, student['math score'][i]], [student['reading score'][i]]*2,
        color='gray', linestyle='--',
        zorder=8)

# y축과 평행한 선
ax.plot([student['math score'][i]]*2, [-3, student['reading score'][i]],
       color='gray', linestyle='--',
       zorder=8)

bbox = dict(boxstyle="round", fc='wheat', pad=0.2)
arrowprops = dict(
    arrowstyle="->")

ax.annotate(s=f'This is #{i} Studnet',
            xy=(student['math score'][i], student['reading score'][i]),
            xytext=[80, 40],
            bbox=bbox,
            arrowprops=arrowprops,
            zorder=9
           )

plt.show()

image-20221009131050012

댓글남기기