소란한 블로그
[matplotlib, seaborn] exponential(scientific) notation 변환 e 표기법 일반 표기법으로 바꾸기 본문
[matplotlib, seaborn] exponential(scientific) notation 변환 e 표기법 일반 표기법으로 바꾸기
소란 2021. 2. 8. 14:46matplotlib으로 plot을 그리다보면 표기법이 exponential notation (e notation)으로 바뀌어서 그려지기도 한다.
이렇게 자동으로 바꿔서 표기해주는 것이 편할 때도 있지만 의도한 것이 아닐 때, 일반 표기법으로 바꿔서 표기해주는 것이 필요하다.
대부분 구글에 (쓰인 plot 함수이름 + exponential notation)과 같은 형식으로 검색하면 스택오버플로우에 자세히 나와있긴 하지만, 그래도 블로그에 정리해본다.
- seaborn의 heatmap의 경우,
import seaborn as sns
import matplotlib.pyplot as plt
fig = plt.figure()
sns.set(rc={'figure.figsize':(15, 10)})
ax = sns.heatmap(trend_heatmap_count.iloc[:, -10:], annot=True, cmap='Oranges')
ax
아무런 설정을 해주지 않았을 때 아래의 차트 처럼 e notation으로 표기된다.

e notation을 일반 표기법으로 바꿔주고 싶다면, heatmap 함수의 파라미터 fmt를 'g'로 설정해주면 된다.
fig = plt.figure()
sns.set(rc={'figure.figsize':(15, 10)})
ax = sns.heatmap(trend_heatmap_count.iloc[:, -10:], annot=True,
cmap='Oranges', fmt='g') # fmt='g': e-notation을 일반표기법으로
ax
그러면 아래 차트처럼 바꿀 수 있다.

- matplotlib의 plot_confusion_matrix일 경우,
from sklearn.metrics import plot_confusion_matrix # confusion matrix 그리는 함수
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
pcm = plot_confusion_matrix(pipe, X_val, y_val,
cmap=plt.cm.Blues,
ax=ax);
plt.title(f'Confusion matrix, n = {len(y_val)}', fontsize=15)
plt.show()
이렇게 코드를 작성하면 아래 처럼 e표기법으로 자동으로 바꿔서 나온다.

해결 방법은 아주 간단한데, plot 함수의 parameter 중 values_format 을 ''으로 정해주는 것이다.
fig, ax = plt.subplots()
pcm = plot_confusion_matrix(pipe, X_val, y_val,
cmap=plt.cm.Blues,
ax=ax, values_format = ''); ## exponential(scientific) notation 바꾸기
plt.title(f'Confusion matrix, n = {len(y_val)}', fontsize=15)
plt.show()

그러면 이렇게 일반적인 표기법으로 차트를 그릴 수 있다.
아마 values_format parameter의 default 값이 e notation으로 되어있는 것 같다.
이렇게 변환해보면 알 수 있는 것 중 하나는 e notation을 이용하면 숫자를 더 간결하게 표기할 수 있다는 것이다.
위의 예는 숫자가 아주 크지 않아서 기본 표기법이 더 직관적으로 다가오겠지만, 숫자가 천문학적으로 커지거나, 작아질 경우 e notation을 이용하면 더 쉽게 비교할 수 있다.
사용하는 plot마다 표기하는 파라미터가 다르기 때문에 필요하다면 그때 그때 검색해서 바꿔주어야 할 것 같다.