Python/matplotlib

[matplotlib] pyplot 정리

Unlimited Jun 2024. 9. 20. 20:16

작성일자 : 2024-09-20

수정일자 : 2024-09-22

Ver 0.1.3

참고 사이트

 

matplotlib.pyplot — Matplotlib 3.9.2 documentation

matplotlib.pyplot matplotlib.pyplot is a state-based interface to matplotlib. It provides an implicit, MATLAB-like, way of plotting. It also opens figures on your screen, and acts as the figure GUI manager. pyplot is mainly intended for interactive plots a

matplotlib.org

 


그리기

# 라이브러리 불러오기
import matplotlib.pyplot as plt

(데이터, 여러 옵션 및 서식) ...

# 그래프 그리기
plt.show()

# ---------------------------------------------------
# 데이터
plt.plot(y) #x를 입력하지 않으면 자동으로 [1,2,3, ...]으로 입력됨
plt.plot(x, y)
plt.plot(x, y, '<type>')
plt.plot(x1, y1, '<type1>', x2, y2, '<type2>', x3, y3, '<type3>')

data_dict = {'data_x' :[], 'data_y' : []}
plt.plot('data_x', 'data_y', data = data_dict)

# ---------------------------------------------------
# 선 종류 (다양한 선 종류 : <LINK>)
## 방법 1
plt.plot(x, y, '<type>')
## '-' : Solid / '--' : Dashed / ':' : Dotted / '-.' : Dash-dot

## 방법 2 : tuple
plt.plot(x, y, linestyle = (<type>))

### (0, (1, 1)) : Sold / (0, (1, 5)) : Dashed 
### (0, (5, 1)) : Dotted /  (0, (3, 5, 1, 5)) : Dash-dot

## 끝 모양 지정
plt.plot(x, y, solid_capatyle = '<type>', dash_capstyle = '<type>')
## 'butt' : 뭉뚝한 / 'round' : 둥근

# ---------------------------------------------------
# 마커 (다양한 종류 : <LINK>
## 방법 1
plt.plot(x, y, '<type>') #color - shape - solid line 순서 ex) 'bo-'

## 방법 2
plt.plot(x, y, marker = '<type>')

# ---------------------------------------------------
# 색상 
plt.plot(x, y, color = '<type>')
## type에는 키워드 인자 or HEX Code (#......) 입력

# ---------------------------------------------------
# 영역 채우기
## 기본 채우기
plt.fill_betweenx(y[array], x[array], alpha = <number>)

## 두 그래프 사이 채우기
plt.fill_between(x[array], y1[array], y2[array], alpha = <number>)

## 다각형 채우기
plt.fill([xlist], [ylist], alpha = <number>)

# ---------------------------------------------------
# 수평 / 수직 참조선 표시
## 수평선
plt.axhline(y # 수평선 위치
           ,xmin # 0 ~ 1 (왼쪽 끝 ~ 오른쪽 끝)
           ,xmax # 0 ~ 1 (왼쪽 끝 ~ 오른쪽 끝)
           ,colors = '<color>'
           ,linestyle = '<linestyle>')

plt.hlines(y # 수평선 위치
          ,xmin # 점 (xmin,y)
          ,xmax # 점 (xmax,y)
          ,colors = '<color>'
          ,linestyle = '<linestyle>')

## 수직선
plt.axvline(x # 수직선 위치
           ,ymin # 0 ~ 1 (아래쪽 끝 ~ 위쪽 끝)
           ,ymax # 0 ~ 1 (아래쪽 끝 ~ 위쪽 끝)
           ,colors = '<color>'
           ,linestyle = '<linestyle>')

plt.vlines(x # 수직선 위치
          ,ymin # 점 (ymin,x)
          ,ymax # 점 (ymax,x)
          ,colors = '<color>'
          ,linestyle = '<linestyle>')

# ---------------------------------------------------
# 여러개 그래프 그리기
## 방법 1
ax1 = plt.subplot(nrows, ncols, index)
...
ax2 = plt.subplot(nrows, ncols, index
                 ,sharex = ax1 # x축 공유
                 ,sharey = ax1 # y축 공유)
plt.tight_layout()
plt.show()

## 방법 2
fig, (ax1, ax2, ax3, ...) = plt.subplots(<rows>, <columns>)

ax1.plot()
ax2.plot()
ax3.plot()
...

## 방법 3
fig, axs = plt.subplots(<rows>, <columns>)

axs[0,0].plot()
axs[0,1].plot()
axs[1,0].plot()
axs[1,1].plot()
...

# ---------------------------------------------------
# 여러개 그래프 사이즈 (row, col)
matplotlib.pyplot.subplot2grid(shape # (<int>, <int>) : Number of rows and of columns of the grid in which to place axis.
                              ,loc  # (<int>, <int>) : Row number and column number of the axis location within the grid.
                              ,rowspan = <number> # defualt = 1, Number of rows for the axis to span downwards.
                              ,colspan = <number> # defualt = 1, Number of columns for the axis to span to the right.
                              ,fig = None # optional, Figure to place the subplot in. Defaults to the current figure.
                              ,**kwargs) # Additional keyword arguments are handed to add_subplot.

# ---------------------------------------------------
# 여러개 그래프 사이즈 (비율)
from matplotlib import gridspec

fig = plt.figure(figsize=(x, y)) 
gs = gridspec.GridSpec(nrows = 3 # row 몇 개 
                      ,ncols = 2 # col 몇 개  
                      ,height_ratios = [list]
                      ,width_ratios = [list])

ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(x, y)
...

plt.show()

 


축, 범례, 그리드, 제목

# 축 레이블 (레이블, 여백, 폰트, 위치)

font1 = {'family' : '<font>'
        ,'color' : '<color'>
        ,'weight' : '<weight>'
        ,'size': <number>}

font2 = {'family' : '<font>'
        ,'color' : '<color'>
        ,'weight' : '<weight>'
        ,'size': <number>}

plt.xlabel('X-Label'
          ,labelpad = <number>
          ,fontdic = font1
          ,loc = '<loc>') # 위치

plt.ylabel('Y-Label'
          ,labelpad = <number>
          ,fontdic = font2
          ,loc = '<loc>')

## loc 옵션 : x = ({'left', 'center', 'right'}) / y = ({'bottom', 'center', 'top'})

# ---------------------------------------------------
# 범례 (위치, 열 개수, 폰트, 테두리, 그림자) 

plt.legend(loc = (<x>,<y>))
## loc = (0.0, 0.0) - 왼쪽 아래 / loc = (1.0, 1.0) - 오른쪽 위

plt.legend(loc = 'lower right'
          ,ncols = <number>
          ,fontsize = <number>
          ,frameon = <T/F> # 테두리
          ,shadow = <T/F>) # 그림자

# ---------------------------------------------------
# 축 범위

## 방법 1
plt.xlim([<xmin>,<xmax>])
plt.ylim([<ymin>,<ymax>])

## 방법 2
plt.axis((<xmin>,<xmax>,<ymin>,<ymax>))
plt.axis((<xmin>,<xmax>,<ymin>,<ymax>))

## 방법 3
plt.axis('on' | 'off' | 'equal' | 'scaled' | 'tight' | 'normal' | 'image' | 'square')

# ---------------------------------------------------
# 축 스케일
plt.xscale('<scale>')
plt.yscale('<scale>')

## x : 'symlog' / y : 'linear', 'log'

# ---------------------------------------------------
# 축 그리드
plt.grid(True
        ,axis = 'x' | 'y'
        ,color = '<color>'
        ,alpha = <number>
        ,linestyle = '<style>')

# ---------------------------------------------------
# 눈금
plt.xticks([list], label = ['list'])
plt.yticsk([lsit], label = ['list'])

# 눈금 스타일
plt.tick_params(axis = 'x' | 'y' | 'both' # 설정이 적용될 축
               ,direction = 'in' | 'out' | 'inout' # 눈금이 안/밖/안밖 표시
               ,lenth = <number> # 눈금 길이
               ,pad = <number> # 여백
               ,labelsize = <number> # 레이블 크기
               ,labelcolor = '<color>' # 레이블 색상
               ,top|bottom|left|right = True | False # 눈금이 표시될 위치
               ,width = <number> # 눈금의 너비
               ,color = '<color>')

# ---------------------------------------------------
# 제목
plt.title('<title>'
          ,loc = '<loc>' # 위치 : 'left', 'center', 'right'
          ,pad = <number> # 여백
          ,fontdic = '<fontstyle>' # 축 레이블과 동일한 형태

plt.title(...).get_position() # 텍스트 위치
plt.title(...).get_text() # 텍스트 문자열

그래프 종류

# 막대 (Bar Graph)
plt.bar(x, value
       ,color = ['<list>']
       ,width = <number> #default : 0,8
       ,align = # 눈금과 막대 위치, default : 'center'
       ,edgecolor = '<color>' # 막대 테두리 색
       ,linewidth = <number> # 테두리 두께
       ,tick_label = list | array) # 눈금에 문자열을 순서대로 나타냄

# ---------------------------------------------------
# 수평 막대 (Horizontal Bar Graph)
plt.barh(y, value
        ,height = <number> #default : 0,8
        ,align = # 눈금과 막대 위치, default : 'center'
        ,edgecolor = '<color>' # 막대 테두리 색
        ,linewidth = <number> # 테두리 두께
        ,tick_label = list | array) # 눈금에 문자열을 순서대로 나타냄
        
# ---------------------------------------------------
# 산점도 (Scatter Plot)
plt.scatter(x,y
           ,s = <number> # 마커 크기
           ,c = <color> # 색상(숫자 시퀀스, RGB, Hex Code)
           ,alpha = <number> # 투명도 0 ~ 1
           ,cmap = '<type>') # 컬러맵 ex) 'Spectral'

# ---------------------------------------------------
# 3차원 산점도 (3D Scatter Plot)
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize = (x,y)
ax = fig.add_subplot(111, projection = '3d')

ax.scatter(x,y,z
          ,s = <nuber>
          ,c = <color> # 색상(숫자 시퀀스, RGB, Hex Code)
          ,alpha = <number> # 투명도 0 ~ 1
          ,cmap = '<type>') # 컬러맵 ex) 'Spectral'

# ---------------------------------------------------
# 히스토그램 (Histogram)
plt.his([List]
        ,bins = <number> # 구간 개수 default = 10
        ,label = '<label>'
        ,cumulative = True | False # 누적 여부 default = False
        ,histtype = '<type>' # 종류 : 'bar', 'barstacked', 'step', 'stepfilled'
        ,density = True # 밀도 함수, 면적 합 = 1
        ,alpha = <number>) # 투명도 0 ~ 1

# ---------------------------------------------------
# 오차 막대 (Error Bar)
plt.errorbar(x, y
            ,yerror = [yerror] # list = [], list = [(), ()] # 비대칭 편차
            ,uplims = True | False # 상한 기호
            ,lolims = Ture | False) # 하한 기호

# ---------------------------------------------------
# 파이 차트 (Pie Chart)
plt.pie([ratio] # list 
       ,lables = ['<labels>'] # list
       ,autopct = '<format>' # 숫자 형식 ex) '%.1f%%' - 소수점 한자리
       ,startangle = <number> # 부채꼴이 그려지는 시작 각도 default = 0
       ,counterclock = False # 시계 방향 순서
       ,explode = [explode] # list, 중심에서 벗어나는 정도
       ,shadow = True # 그림자 표시
       ,colors = [colors] # list, 색상
       ,wedgeprops = {dictionary}) # dictionary, 'width' / 'edgecolor' / 'linewidth' # 도넛 차트

# ---------------------------------------------------
# 히트맵 (Heatmap)
cmp = plt.get_cmap('<type>')
plt.matshow([2D array | list]
           ,cmap = cmap # 컬러맵 종류 ex) 'PiYG', 'BuGn', 'Greys', 'bwr') 
plt.colorbar(shrink = <number> # 크기, default = 1.0
            ,aspect = <number> # 종횡비, default = 20)
plt.clim(min, max) # 색상 범위 지정

# ---------------------------------------------------
# 상자 수염 그림 (Box plot, Box-Whisker plot)
fig, ax = plt.subplots()

ax.boxplot([data arry] # data array
          ,notch = True # 중앙값(Median)의 95% 신뢰 구간을 노치 형태로 표시
          ,whis = <number> # 수염의 길이, 수염 범위 밖 데이터 표시 여부 ex) 2.5 
          ,vert = Falsue) # 수평 방향의 Box plot, default는 수직 방향

whiskers = [item.get_ydata() for item in box['whiskers']] # Q1, Q3, max, min
medians = [item.get_ydata() for item in box['medians']] # 중앙값
fliers = [item.get_ydata() for item in box['fliers']] # 수염 범위 밖 데이터 (outliers)

# ---------------------------------------------------
# 바이올린 플롯 (Violin plot)
fig, ax = plt.subplots()

ax.violinplot([data array] # data array
             ,position = [list] # 위치 지정, default는 1,2,3,...
             ,showmeans = True # 평균값 위치 표시 default = False
             ,showextrema = False # 최대/최소 표시 default = True
             ,showmedians = True # 중앙값 표시 default = False
             ,quantiles = [list array]) # 분위수 지정

ax.set_ticks([list])  

violin['bodies'][<number>].set_facecolor('<color>') # n번째 바이올린 분포의 채워진 영역
viloin['cbars'].set_edgecolor('<color>') # 바이올린 분포의 중심
viloin['cmaxes'].set_edgecolor('<color>') # 바이올린 분포의 최대값
viloin['cmins'].set_edgecolor('<color>') # 바이올린 분포의 최소값
viloin['cmeans'].set_edgecolor('<color>') # 바이올린 분포의 평균값
viloin['cmedians'].set_edgecolor('<color>') # 바이올린 분포의 중앙값
viloin['cquantiles'].set_edgecolor('<color>') # 바이올린 분포의 분위값
           
plt.show()