파이썬으로 지수함수 그래프 그리기

2021. 4. 27. 08:17캐리의 데이터 세상/파이썬

반응형

 

파이썬으로 지수함수를 그래프로 표현해 보겠습니다. 앤드류 응 코세라 딥러닝 강의를 들을 때 첫 강의부터 지수와 로그들이 쏟아지면서 이를 코드로 풀어서 설명했던 기억이 스멀. 고등학교 때 배웠던 지수 로그의 기억이 날듯 말듯한 상태였으니 받아들이는 양도 그에 비례하겠죠.. 아침에 뇌를 깨울 겸 보고 있는 기초수학 책 한 챕터씩 따라 해보고 있습니다ㅎ 예제 코드들을 조금씩 변형해 보면서 matplotlib 활용 범위도 늘려볼 수 있을 듯합니다.

 

1. 지수함수

* 지수함수란 거듭제곱 꼴의 함수 

 $$ y=a^x$$

  • a를 밑, x를 지수. a가 변수가 아니라 x가 변수라는 점 ***
  • 주어진 a가 있고, 입력 x가 들어오면 a를 x번 곱해서 y로 출력하라는 의미

 

 

밑 2,3,4와 ½, ⅓, ¼인 경우 그래프 비교해 보기

책 저자의 깃 헙 코드 참조

fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
fig.set_size_inches((15,6))

ax1.xaxis.set_tick_params(labelsize=20)
ax1.yaxis.set_tick_params(labelsize=20)

x = np.linspace(-2, 2, 100)
a1, a2, a3 = 2, 3, 4
y1, y2, y3 = a1**x, a2**x, a3**x 

ax1.plot(x, y1, color='b', label=r"$2^x$") #color 조정
ax1.plot(x, y2, '--', color='r', label=r"$3^x$")
ax1.plot(x, y3, ':', color='m', label=r"$4^x$")
    
ax1.set_xlabel('$x$', fontsize=35)
ax1.set_ylabel('$y$', fontsize=35)
ax1.legend(fontsize=20)

ax2.xaxis.set_tick_params(labelsize=18)
ax2.yaxis.set_tick_params(labelsize=18)

x = np.linspace(-2, 2, 100)
a1, a2, a3 = 1/2, 1/3, 1/4
y1, y2, y3 = a1**x, a2**x, a3**x 

ax2.plot(x, y1, color='b', label=r"$(1/2)^x$")
ax2.plot(x, y2, '--', color='r', label=r"$(1/3)^x$")
ax2.plot(x, y3, ':', color='m', label=r"$(1/4)^x$")
    
ax2.set_xlabel('$x$', fontsize=20)
ax2.set_ylabel('$y$', fontsize=20)
ax2.legend(fontsize=20)

arrowed_spines(fig, ax1)
arrowed_spines(fig, ax2)

if file_print == True :
    fig.savefig("img/fig2-11.png", dpi=300, bbox_inches='tight')

plt.show()

 

지난 1차 함수 코드 포스팅에서 사용했던 기본 def 및 함수들을 불러왔다고 했을 때의 코드입니다. matplotlib 사용법을 좀 더 익히기 위해 그래프 선 색깔을 바꿔 봤습니다:) magenta가 무슨 색깔인지 궁금했는데 자주색이었군요. 영어 단어 하나 알아가네요^^ 링크의 matplotib 다큐멘트에서 컬러 사용법 참고하세요!

{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}, they are the single character short-and notations for blue, green, red, cyan, magenta, yellow, black, and white (source : matplotlib tutorial)

지수함수-그래프
지수함수 그래프

 

 

지수함수와 이차 함수 비교

 

지수함수의 빠른 증가를 이차함수와 비교해 봅니다. 

지수함수와 이차함수

 

fig, ax = plt.subplots(1, 1)
fig.set_size_inches((6,8))

ax.xaxis.set_tick_params(labelsize=18)
ax.yaxis.set_tick_params(labelsize=18)

x = np.linspace(0, 10)

y1 = x**2
y2 = 2**x

plt.plot(x, y1, '--', color='r', label=r"$x^2$")
plt.plot(x, y2, color='b', label=r"$2^x$")
    
plt.legend(loc="upper right",fontsize=25) # 범례 표시 : loc 부분 변경해보기
plt.xlabel('$x$', fontsize=25)
plt.ylabel('$y$', fontsize=25)

arrowed_spines(fig, ax)

if file_print == True :
    fig.savefig("img/fig2-12.png", dpi=300, bbox_inches='tight')

plt.show()

여기서는 plt.legend 범례 표시의 위치를 살짝 바꿔봤습니다.

The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure. The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure. [matplotlib docs 참고]

 

오늘의 큰 소득은... 제곱근, 로그 등 수학 식들을 포스팅할 때 어떻게 표현하는지 찾아보고 알게 되었다는 것! 여태 궁금하면서도 a의 제곱이면 a^2로 직관적으로 쓰기만 했는데, markdown 코드를 html 편집 head 부분에 넣고 $$안으로 감싸 주기만 하면 됩니다! 다음 포스팅에서 정리해 볼게요! (다른 방법이 인긴 합니다. 한글 ㅊ+한자 단축키 누르면 ⅜ 2² 와 같이 기본 숫자로 분수, 제곱은 만들 수 있지만 일반식으로 나타내는 건 힘들기에 markdown 사용!)

 

반응형