1-2. Matplotlib 실습

유승우·2022년 5월 11일
0

Maplotlib


  • numpy와 scipy를 베이스로 하여 다양한 라이브러리와 호환성이 좋다.
  • 코드상에서 일반적으로 matplotlib은 줄여서 mpl로 사용한다.

기본 plot


  • matplotlib 에서 그리는 시각화는 figure 라는 큰 틀에 ax라는 서브 플롯을 추가해서 만든다.

  • plt.figure(figsize=(가로,세로))를 통해 큰 틀의 크기를 조정할 수 있다.

  • 서브 플롯의 추가는 add.subplot(행,열,위치)로 할 수 있으며, 2개 이상 그리고 싶은 경우 위치를 지정해주어야 한다.

fig = plt.figure(figsize=(12, 7)) # 큰 틀의 크기 지정

ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)

# 아래와 같이 붙여서도 사용이 가능하지만 가독성이 떨어진다.
# ax1 = fig.add_subplot(211)
# ax2 = fig.add_subplot(212)

plt.show() # 차트 그리기
  • 서브 플롯에 차트 그리기
    • Pyplot API : 순차적 방법

      fig = plt.figure()
      
      x1 = [1, 2, 3]
      x2 = [3, 2, 1]
      
      ax1 = fig.add_subplot(211) 
      plt.plot(x1) # ax1에 그리기
      ax2 = fig.add_subplot(212) 
      plt.plot(x2) # ax2에 그리기
      plt.show()
    • 객체지향 API : 그래프에서 각 객체에 대해 직접적으로 수정하는 방법

      fig = plt.figure()
      
      x1 = [1, 2, 3]
      x2 = [3, 2, 1]
      
      ax1 = fig.add_subplot(211)
      ax2 = fig.add_subplot(212) 
      
      ax1.plot(x1) # ax1에 그리기
      ax2.plot(x2) # ax2에 그리기
      plt.show()
  • 한 서브 플롯에서는 동시에 다양한 그래프를 그릴 수 있으며, 같은 종류에 한해 색상이 자동적으로 구분된다.
fig = plt.figure()
ax = fig.add_subplot(111) 
# 3개의 그래프 동시에 그리기
ax.plot([1, 1, 1]) # 파랑
ax.plot([1, 2, 3]) # 주황
ax.plot([3, 3, 3]) # 초록 

plt.show()
  • 색상 지정하기
    • 색상은 다음과 같이 세 가지 방법으로 지정할 수 있다.
fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot([1, 1, 1], color='r') # 한 글자로 정하는 색상
ax.plot([2, 2, 2], color='forestgreen') # color name
ax.plot([3, 3, 3], color='#000000') # hex code (BLACK)
plt.show()
  • 제목/범례 지정하기
fig = plt.figure()
ax = fig.add_subplot(111) 
ax.plot([1, 1, 1], label='1') 
ax.plot([2, 2, 2], label='2') 
ax.plot([3, 3, 3], label='3')
ax.set_title('Basic Plot') # 제목지정
ax.legend() # 범례지정
plt.show()
  • 축 범위 지정하기
fig = plt.figure()
ax = fig.add_subplot(111) 
ax.plot([1, 1, 1], label='1') 
ax.plot([2, 2, 2], label='2') 
ax.plot([3, 3, 3], label='3')

ax.set_title('Basic Plot')
ax.set_xticks([0, 1, 2]) # x축 범위 지정
ax.set_xticklabels(['zero', 'one', 'two']) # x축에 적히는 텍스트 수정
# ax.set_yticks([0, 1, 2]) # y축 범위 지정
# ax.set_yticklabels(['zero', 'one', 'two']) # y축에 적히는 텍스트 수정
ax.legend()

plt.show()
  • 일반적인 텍스트 추가하기

    • text : 원하는 위치의 텍스트를 적어주는 느낌으로, x축과 y축,텍스트를 넣는다.

      fig = plt.figure()
      ax = fig.add_subplot(111) 
      ax.plot([1, 1, 1], label='1') 
      ax.plot([2, 2, 2], label='2') 
      ax.plot([3, 3, 3], label='3')
      
      ax.set_title('Basic Plot')
      ax.set_xticks([0, 1, 2])
      ax.set_xticklabels(['zero', 'one', 'two'])
      
      ax.text(x=1, y=2, s='This is Text')
      
      ax.legend()
      
      plt.show()
    • annotate : 원하는 위치의 text를 지정하고, 그 포인트를 지정해주는 것으로 화살표와 같은 기능을 사용할 수 있다.

      fig = plt.figure()
      ax = fig.add_subplot(111) 
      ax.plot([1, 1, 1], label='1') 
      ax.plot([2, 2, 2], label='2') 
      ax.plot([3, 3, 3], label='3')
      
      ax.set_title('Basic Plot')
      ax.set_xticks([0, 1, 2])
      ax.set_xticklabels(['zero', 'one', 'two'])
      
      ax.annotate(text='This is Annotate', xy=(1, 2), # x,y 값 지정
                 xytext=(1.2, 2.2), # 텍스트 정보지정
                  arrowprops=dict(facecolor='black'), # 화살표 지정
                 )
      
      ax.legend()
      
      plt.show()

0개의 댓글