본문 바로가기

Python

[Python] 그래프 축(axis)에 단위 표현하기

반응형

Python의 matplotlib을 이용해서 graph를 그릴 때, x축과 y축에 단위를 넣고 싶을 때가 있다. 

이럴 때는 axis의 Formatting을 해 줌으로써 표현할 수 있다. 

 

코드는 다음과 같다. 

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker  

#테스트 데이터
x = [i * 55 for i in range(1, 11)]
y = [0.219, 0.402,  0.543,  0.646,0.765,  0.880,1.169, 1.358,1.492,1.611]

#단위 생성
plt.gca().xaxis.set_major_formatter(mticker.FormatStrFormatter('%.1f s'))
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.1f m'))

plt.plot(x, y)
plt.savefig('test',dpi=300)
plt.show()

결과를 살펴보자. 

 

다음과 같이 x축과 y축에 각각 's' 와 'm'단위가 들어간 것을 확인할 수 있다. 

만약 다음과 같이 바꾸면 어떻게 될까?

plt.gca().xaxis.set_major_formatter(mticker.FormatStrFormatter('s'))
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('m'))

이렇게 되면 x축과 y축에 아무런 정보도 표시되지 않고, m와 s만 표시된다. 다음과 같이 말이다.

따라서, 제대로 정보를 표기해주기 위해서는 꼭 소수점 몇자리까지 표기해줄지를 알려주어야 한다.

정수일 경우에는 다음과 같이 '%i (unit)' 을 해주면 되고, 

plt.gca().xaxis.set_major_formatter(mticker.FormatStrFormatter('%i s'))
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%i m'))

소수일 경우에는 다음과 같이 '%.(n)f (unit)' 표현을 통해 소수점 밑 n번째 자리까지 표현해줄 수 있다.

예를 들어 소수 세번째 자리까지 표기해주고 싶은 경우, '%.3f' 이다.

plt.gca().xaxis.set_major_formatter(mticker.FormatStrFormatter('%.3f s'))
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.3f m'))