본문 바로가기

인공지능/Python

Python 그래프 부드럽게 그리기 (Python plot line smooth)

Problem

matplotlib.pyplot을 이용해 plot을 그리려고하는데 time scale이 달라서 모양이 이쁘지 않게 나오는 경우가 있다.

아래 plot에서 origin은 time step interval이 1이고, wavelet_n 은 time step interval이 2**n으로 나오게 된다. 즉 wavelet_5는 두 값간의 time step interval이 32로 나오게 되서 굉장히 딱딱한 모양이 나오게 되며, 경향성을 알기도 어렵다.

 

Solution

scipy의 make_interp_spline함수를 이용해 해결했다.

예시 코드는 다음과 같다.

# example
origin_y = [10,5,2,6,20,30]
origin_x = [0,4,8,12,16,20] # time step interval = 4

# original data input
cubic_interploation_model=make_interp_spline(origin_x,origin_y)

# smooth line output
xs=np.linspace(0,len(origin_x)*4,len(origin_x)*4)
ys=cubic_interploation_model(xs)

# to plot
plt.plot(xs, ys)

 

실제 적용 결과는 다음과 같다.

훨씬 부드러워져서 경향성을 파악하기 쉬워졌다.