Lecture 강의

Undergraduates 학부 Graduates 대학원 Lecture 역학 Lecture 설계 Lecture IT(IoT, AI) Lecture SAP2000 Lecture 아바쿠스 Lecture 파이썬 Lecture 엑셀 VBA Lecture 마이다스 Lecture 이탭스

[03. 패키지 - Matplotlib] (1) 기본 사용법(plt.plot), (2) IPython

작성자 : kim2kie

(2023-02-19)

조회수 : 1239

[참조]

 

Matplotlib은 그래프를 그리는 패키지이다.

 

(1) 기본 사용법
 1) 2D plot
 2) 마커, 선, 색상
 3) 주요 함수

(2) IPython
 1) 그래프를 콘솔 내에서 출력할 경우
 2) 그래프를 별도창에 출력하고 interactive하게 사용할 경우
 3) 그래프를 별도창에 출력하고 interactive하지 않게 사용할 경우

 


 

 

(1) 기본 사용법

1) 2D plot

  • Ex)
    import matplotlib.pyplot as plt
    import numpy as np

    x = np.linspace(0,1,50)

    y1 = np.cos(4*np.pi*x)
    y2 = np.cos(4*np.pi*x)*np.exp(-2*x)

    plt.plot(x,y1) # 2D 선그래프
    plt.plot(x,y2)

    plt.show() # 화면 표시. Jupyter나 IPython에서는 자동 표시되므로 필요없음
    (Note: plt.show()는 matlab의 "hold off"와도 같은 기능을 한다.
    따라서 그래프를 여러 개 별도로 그릴 경우 사용해야 한다.)



     

  • Ex-계속) r(raw) 문자열 vs 일반 문자열
    plt.plot(x,y1,'r-*',   # 'r-*': red, solid line
             label=r'$sin(4 \pi x)$',lw=1) # legend label과 line width
             # r을 붙여 만든 raw문자열은 escape 문자(\t, \n 등)가 적용되지 않는다.
    plt.plot(x,y2,'b--o',
             label=r'$ e^{-2x} sin(4\pi x) $',lw=1)
    plt.title(r'$sin(4 \pi x)$ vs. $ e^{-2x} sin(4\pi x)$') # title
    plt.xlabel('x') # x축 label
    plt.ylabel('y') # y축 label
    plt.text(0.5,-1.0,r'This is sample') # (x,y) 위치에 text를 출력
    plt.axis([0,1,-1.5,1.5]) # axis의 범위
    plt.grid(True)
    plt.legend(loc='upper left') # legend location
    plt.tight_layout() # 여백 조정
    plt.show() # 화면 표시 



     

  • Ex-계속) subplot()
    plt.subplot(2,1,1)
    plt.plot(x,y1,'r-*',lw=1)
    plt.grid(True)
    plt.ylabel(r'$sin(4 \pi x)$')
    plt.axis([0,1,-1.5,1.5])

    plt.subplot(2,1,2)
    plt.plot(x,y2,'b--o',lw=1)
    plt.grid(True)
    plt.xlabel('x')
    plt.ylabel(r'$ e^{-2x} sin(4\pi x) $')
    plt.axis([0,1,-1.5,1.5]) 

    plt.tight_layout() 
    plt.show()


     

2) 마커, 선, 색상
 

  • Markers
    '.'  # point marker
    ','  # pixel marker
    'o'  # circle marker
    'v'  # triangle_down marker
    '^'  # triangle_up marker
    '<'  # triangle_left marker
    '>'  # triangle_right marker
    '1'  # tri_down marker
    '2'  # tri_up marker
    '3'  # tri_left marker
    '4'  # tri_right marker
    '8'  # octagon marker
    's'  # square marker
    'p'  # pentagon marker
    'P'  # plus (filled) marker
    '*'  # star marker
    'h'  # hexagon1 marker
    'H'  # hexagon2 marker
    '+'  # plus marker
    'x'  # x marker
    'X'  # x (filled) marker
    'D'  # diamond marker
    'd'  # thin_diamond marker
    '|'  # vline marker
    '_'  # hline marker

  • Line Styles
    '-'  # solid line style
    '--' # dashed line style
    '-.' # dash-dot line style
    ':'  # dotted line style

  • Colors
    'b'  # blue
    'g'  # green
    'r'  # red
    'c'  # cyan
    'm'  # magenta
    'y'  # yellow
    'k'  # black
    'w'  # white

  • Example format strings:
    'b'   # blue markers with default shape
    'or'  # red circles
    '-g'  # green solid line
    '--'  # dashed line with default color
    '^k:' # black triangle_up markers connected by a dotted line

     

3) 주요 함수

  • plot()
    subplot()
    title()
    xlabel()
    ylabel()
    axis()
    xlim()
    ylim()
    tight_layout()
    grid()
    legend()
    show()
    figure()
    text()
    subplots()
    xscale(...) : xscale("log")이면 로그스케일
    minorticks_on(), minorticks_off()
    grid(True, which='both')
    yscale(...) 

 

(2) IPython 

  • IPython(Interactive Python) 콘솔에서 interactive(대화형)하게 그래프를 그릴 수 있다.
    "%matplotlib"이라는 magic command와 "matplotlib.pyplot.ion()", "matplotlib.pyplot.ioff()"를 통해 제어한다.

     

1) 그래프를 콘솔 내에서 출력할 경우

  • Ex)
    [1] %matplotlib inline

    # plt.plot() 같은 명령이 있을 때마다 콘솔 내에 출력
    # plt.show() 를 호출하지 않아도 됨


2) 그래프를 별도창에 출력하고 interactive하게 사용할 경우
 

  • Ex)
    [1] %matplotlib qt5
    [2] matplotlib.pyplot.ion()

    # plt.plot() 등을 호출하면 바로 그래프가 업데이트
    # plt.show()를 호출할 필요가 없음

 

  • Ex)
    [1] %matplotlib qt5
    [2] matplotlib.pyplot.ioff()

    # plt.plot() 등을 호출후 plt.show()를 호출해야 그래프가 업데이트