Line Plot
Matplotlib에서 선 그래프는 plot()을 통해 그릴 수 있습니다. plot()은 기본적으로 plot(x, y, fmt)으로 구성되며, fmt은 marker(데이터 표시), color(색), line(선 스타일)으로 구분됩니다. x, y는 별도 인자 선언없이 순서대로 넣어주면 되고, 나머지는 선언을 해주고 값을 입력하여 파라미터를 전달하는 과정이 필요합니다. 다만, plt를 통해 제공하고 있는 기능은 매우 다양하니, 필요할 때마다 찾아보는 습관이 필요합니다.
matplotlib.pyplot.plot — Matplotlib 3.9.2 documentation
An object with labelled data. If given, provide the label names to plot in x and y. Note Technically there's a slight ambiguity in calls where the second label is a valid fmt. plot('n', 'o', data=obj) could be plt(x, y) or plt(y, fmt). In such cases, the f
matplotlib.org
실습 1. sin / cos 그래프 그리기
Numpy 함수로 0에서 2파이까지 구간을 1000개로 쪼갠 x와 sin, cos 함수값인 y를 생성하여 아래와 같이 만들 수 있습니다.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
fig = plt.figure(figsize=(12,5))
ax = fig.add_subplot(111, aspect=1)
ax.plot(x, y1,
color='blue',
linewidth=2, label='sin')
ax.plot(x, y2,
color='red',
linewidth=2, label='cos')
ax.legend(loc='upper center')
plt.show()
실습 2. 축 추가 (Secondary axis)
과학, 공학에서 x,y 축 외에 추가적인 축으로 설명이 필요한 경우가 있습니다. (예를 들어, 각도는 라디안과 ∘로 표기하고 그 값이 입력된 sin값 등) 이럴 경우 축을 추가할 수 있는데 ax 클래스에 secondary_xaxis, secondary_yaxis를 통해 추가 가능합니다. [1]
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(layout='constrained')
x = np.arange(0, 360, 1)
y = np.sin(2 * x * np.pi / 180)
ax.plot(x, y)
ax.set_xlabel('angle [degrees]')
ax.set_ylabel('signal')
ax.set_title('Sine wave')
def deg2rad(x):
return x * np.pi / 180
def rad2deg(x):
return x * 180 / np.pi
secax = ax.secondary_xaxis('top', functions=(deg2rad, rad2deg))
secax.set_xlabel('angle [rad]')
plt.show()
실습 3. 축 및 그래프 추가 (twinx, 보조축)
같은 x축을 공유하면서 맞은 다른 그래프를 추가하는 다른 방법도 존재합니다. twinx를 통해 x를 동일하게 공유하고, 같은데 ax에 추가하는 방법입니다. 아래와 같은 코드로 작성하면 됩니다만, 그래프를 추가할 경우 가독성이 떨어질 우려가 있으니 주의해서 사용할 필요가 있겠습니다.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
np.random.seed(97)
x = np.arange(20)
y1 = np.random.rand(20)
y2 = np.random.rand(20)
# 첫번째 시각화
ax.plot(x, y1, color='blue')
ax.set_ylabel('y1')
# 두번째(보조축) 시각화
ax2 = ax.twinx()
ax2.plot(x, y2, color='tomato')
ax2.set_ylabel('y2')
plt.show()
참고자료
[1] https://matplotlib.org/stable/gallery/subplots_axes_and_figures/secondary_axis.html
'Python > Visualization' 카테고리의 다른 글
Matplotlib을 이용한 막대 그래프 만들기 (bar plot) | 누적 막대 그래프, 비율, 묶은 막대 그래프 (0) | 2024.08.24 |
---|---|
Matplotlib으로 산점도 그리기 (Scatter plot) (0) | 2024.08.23 |
Basemap 위에 국내 발전사업허가 현황 버블차트 그리기 | Matplotlib (0) | 2021.12.20 |
mpl-toolkits.basemap을 활용한 세계 발전소 데이터를 활용한 발전원별, 용량별 현황시각화 | Matplotlib (0) | 2021.11.13 |
파이썬을 활용한 지역별 월전력판매량 시각화하기 | Folium (1) | 2021.09.04 |