728x90
반응형
기본적으로 graph에서 사용되는 line 및 marker의 스타일 (유형, 굵기, 색, 마커)을 변경하는 것은
Axes
에서 제공하는 다양한 graph를 그리는 모든 메서드들에서 필요하기 때문에 공통적인 parameters가 제공됨.
다음이 많이 사용되는 것들을 정리해 놓은 것임.
parameter | desc. | value |
linestyle |
ls 로도 쓰이며, 선의 종류. |
'-' : solid(실선), ':' : dotted(점선), '--' : dashed(파선), '-.' : dashdot(파점선) |
linewidth |
lw 로도 쓰이며, 선의 굵기를 지정 |
float |
color |
선의 색 | 'w' : white 'r' : red 'g' : green 'b' : blue 'y' : yellow : cyan : magenta |
alpha |
투명도 | float, [0.,1.] , 1.인 경우 불투명, 0.인 경우 완전투명 |
markersize |
마커 크기 | float |
markeredgewidth |
마커의 외곽선 굵기 | float |
markerfacecolor |
마커의 색 | color 참고. |
markeredgecolor |
마커의 외곽선 색 | color 참고. |
marker
parameter는 마커의 종류를 결정하며 다음의 값을 가짐.
+
: crosso
: circle*
: star.
: dots
: squarev
: tirangle_down^
: triangle_up<
: tirangle_left>
: triangle_rightp
: pentagonh
: hexagon|
: vline marker_
: hline marker
color 의 경우 앞서 다룬 약어 외에도 다음과 같은 형식들이 사용가능함.
형식 | 예시 | 설명 |
RGB 튜플 | (0.1, 0.2, 0.5) | 빨강, 초록, 파랑 — 각각 0~1 |
RGBA 튜플 | (0.1, 0.2, 0.5, 0.6) | 마지막은 알파 (투명도) |
16진수 | '#ffcc00' | 2자리씩 R, G, B |
색 이름 | 'red', 'blue' | HTML 색 이름 |
예제 코드는 다음과 같음:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as fm
import platform
import os
def set_korean_font():
system = platform.system()
if system == 'Darwin': # macOS
font_name = 'AppleGothic'
elif system == 'Windows':
font_name = 'Malgun Gothic'
elif system == 'Linux':
# 예: Colab이나 Ubuntu
# 나눔고딕이 설치된 경우
font_path = '/usr/share/fonts/truetype/nanum/NanumGothic.ttf'
if os.path.exists(font_path):
font_prop = fm.FontProperties(fname=font_path)
plt.rcParams['font.family'] = font_prop.get_name()
print(f"Success- font configuration: {font_prop.get_name()}")
plt.rcParams['axes.unicode_minus'] = False
return
else:
print("There is not avialble font for Korean.")
return
else:
print("Not Available OS.")
return
# 공통 설정
plt.rcParams['font.family'] = font_name
plt.rcParams['axes.unicode_minus'] = False
print(f"폰트 설정 완료: {font_name}")
# 사용 예시
set_korean_font()
# 데이터 생성
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Figure와 Axes 객체 생성
fig, ax = plt.subplots()
# 그래프 그리기
ax.plot(
x, y,
linestyle='--', # '--' : dashed line
linewidth=2.0, # 선의 굵기
color='b', # 'b' : blue
alpha=0.7, # 투명도
marker='o', # 'o' : 원형 마커
markersize=6, # 마커 크기
markeredgewidth=1.5, # 마커 외곽선 굵기
markerfacecolor='red', # 마커 내부 색상
markeredgecolor='black' # 마커 외곽선 색상
)
# 제목과 축 레이블 설정
ax.set_title('객체 지향 스타일의 그래프')
ax.set_xlabel('X 축')
ax.set_ylabel('Y 축')
# 그리드 추가
ax.grid(True)
# 그래프 표시
plt.show()

앞서 다룬 parameters 는 거의 모든 graph에서 공통적으로 사용된다.
- key-value로 형태로 argument를 지정하는 걸 개인적으로 권하지만,
- formatting string (fmt)으로 이들 값들을 조합하여 positional argument로 한번에 설정하는 경우도 많다.
fmt 문자열은 다음 3가지를 조합:
- 색상 코드 (color): 'r', 'g', 'b', 'k', 'c', 'm', 'y', 'w'
- 마커 스타일 (marker): 'o', 's', '^', 'x', '+', '.', 'D', etc.
- 선 스타일 (linestyle): '-', '--', ':', '-.', 'None'
주로 첫번째, 두번째 argument들은 graph를 그리는데 필수 데이터들 (x,y)에 해당하고,
이들 다음의 position에 fmt
argument가 위치하는게 일반적이다.
다음의 예는 blue, circle, dashed line이 그려지게 된다.
plot[x, y, 'bo--']
다음은 여러 fmt의 예임.
fmt | 의미 |
'ro' | 빨간색 원형 마커만 (선 없음) |
'g--' | 초록색 점선 |
'b-o' | 파란색 실선 + 원형 마커 |
'k^:' | 검은색 점선 + 삼각형 마커 |
'ms--' | 자홍색 점선 + 정사각형 마커 |
'yD' | 노란색 다이아몬드 마커 |
'cx-' | 시안색 실선 + X 마커 |
'r.' | 빨간색 점 마커 (마커만) |
'--' | 기본색 점선 (색 미지정) |
'd' | 마커만 지정 (선, 색 미지정) |
'Python > matplotlib' 카테고리의 다른 글
[matplotlib] 3D Plot (0) | 2024.01.21 |
---|---|
[matplotlib] x축과 y축을 그리기: spines (0) | 2023.08.08 |
[matplotlib] : backend 란 (0) | 2023.07.20 |
[matplotlib]: Figure and Axes (0) | 2023.07.20 |
[Python] matplotlib : Axis Scale and Ticks (0) | 2023.07.14 |