본문 바로가기
Programming/Python

[Matplotlib] 기본

[실무에서...]

 

1.비지니스 이해

2.데이터 이해 (SQL)

3.데이터 준비: 데이터 전처리 (pandas)

수집(e): DBMS/파일/웹

정제(c): 누락치/이상치

변환(가공-t): 피처링 코드 스케일링(정규화, 표준화) -> 하나의 파일

데이터 분석(모델링)
적재(L)

4.모델링

5.평가

6.이관

 


 

 

 

 

import matplotlib.pyplot as plt

plt.plot : 단순 선 그래프

 

 

 

%matplotlib qt   # 창모드 출력 유도

 

 

 

잠깐 numpy 이용한 함수그래프

 

import numpy as np

x = np.arange(-4.5, 5, 0.5) # x의 interval: [-4.5, 5), 0.5 단위.
y = 2*x**2 # 수식으로 x 대응하는 y 생성
[x,y]  # array 출력

plt.plot(x,y)
plt.show()

 

여러 함수 동시 표현하기

 

 

 

 

import numpy as np

x = np.arange(-4.5, 5, 0.5)
y1 = 2*x**2
y2 = 5*x + 30
y3 = 4*x**2 + 10


import matplotlib.pyplot as plt

plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.show()  

# 또는

plt.plot(x, y1, x, y2, x, y3)           # 위 아래 동일 결과 출력!
plt.show()

 

 

 

 

plt.show()는 여러 함수를 한 그래프에 한번에 출력하도록 함

                  즉, 두 개 이상의 그래프를 그릴때 쓰는 함수

 

 

 

또는

 

plt.plot(df1['x'],df1['y'],'o')   # df는 각 df 자료
plt.plot(df2['x'],df2['y'],'o')   # o는 점모양 산점도 유도
plt.plot(df3['x'],df3['y'],'o')
plt.plot(df4['x'],df4['y'],'o')

 

 

 

 

 

나눠그리되 한번에 출력하려면?  -> plt.figure() 중간에 삽입

plt.plot(x, y1) #처음 그리기 함수를 수행하면 그래프 창이 자동으로 생성됨

plt.figure() # 새로운 그래프 창을 생성함
plt.plot(x, y2) # 새롭게 생성된 그래프 창에 그래프를 그림

plt.show()

 

 

 

 

 

 

 

좀 더 상세하게 나눠서 그리기

 

import numpy as np

# 데이터 생성
x = np.arange(-5, 5, 0.1)
y1 = x**2 -2
y2 = 20*np.cos(x)**2 # NumPy에서 cos()는 np.cos()으로 입력

plt.figure(1) # 1번 그래프 창을 생성함
plt.plot(x, y1) # 지정된 그래프 창에 그래프를 그림

plt.figure(2) # 2번 그래프 창을 생성함
plt.plot(x, y2) # 지정된 그래프 창에 그래프를 그림

plt.figure(1) # 이미 생성된 1번 그래프 창을 지정함
plt.plot(x, y2) # 지정된 그래프 창에 그래프를 그림

plt.figure(2) # 이미 생성된 2번 그래프 창을 지정함
plt.clf() # 2번 그래프 창에 그려진 모든 그래프를 지움
plt.plot(x, y1) # 지정된 그래프 창에 그래프를 그림

plt.show()

clf로 그래프 지정을 지울 수 있다.

 

 

 

 

 

 

한 그래프 크기에 여러개 집어넣는 함수 subplot(row개수, col개수, 위치)

 

import numpy as np

# 데이터 생성
x = np.arange(0, 10, 0.1)
y1 = 0.3*(x-5)**2 + 1
y2 = -1.5*x + 3
y3 = np.sin(x)**2 # NumPy에서 sin()은 np.sin()으로 입력
y4 = 10*np.exp(-x) + 1 # NumPy에서 exp()는 np.exp()로 입력

# 2 × 2 행렬로 이뤄진 하위 그래프에서 p에 따라 위치를 지정
plt.subplot(2,2,1) # p는 1
plt.plot(x,y1)

plt.subplot(2,2,2) # p는 2
plt.plot(x,y2)

plt.subplot(2,2,3) # p는 3
plt.plot(x,y3)

plt.subplot(2,2,4) # p는 4
plt.plot(x,y4)

plt.show()

또는 figure, subplot 같이 이용

  1. 전체 그래프의 크기를 정한다. (정하지 않으면 디폴트 크기로 지정된다.)
    plt.figure(figsize=(x사이즈, y사이즈))

  2. 그래프를 그려 넣을 격자를 지정한다.(전체행개수,전체열개수,그래프순서)
    plt.subplot(전체행개수,전체열개수,그래프순서)

  3. 격자에 그래프를 하나씩 추가한다.
plt.figure(figsize=(9,6))
plt.subplot(221)   # 2*2mtx의 1행1열
plt.plot(df1['x'],df1['y'],'o')

plt.subplot(222)
plt.plot(df2['x'],df2['y'],'+')

plt.subplot(223)
plt.plot(df3['x'],df3['y'],'*')

plt.subplot(224)
plt.plot(df4['x'],df4['y'],'d')

 

응용하기

fig = plt.figure(figsize=(9,6), facecolor='ivory')

plt.subplot(221)
plt.plot(df1['x'],df1['y'],'o')
plt.title('ax1')

plt.subplot(222)
plt.plot(df2['x'],df2['y'],'+')
plt.title('ax2')

plt.subplot(223)
plt.plot(df3['x'],df3['y'],'*')
plt.title('ax3')

plt.subplot(224)
plt.plot(df4['x'],df4['y'],'d')
plt.title('ax4')

fig.suptitle('Amscombe', size=20)
fig.tight_layout()

 

 

figure, axes

  • figure : 그림이 그려지는 캔버스
  • axes : 하나의 그래프

위치, 크기 지정하여 그래프 그리기

  1. figure 객체를 생성한다.
    fig = plt.figure(figsize=(가로길이,세로길이))

  2. figure객체의 add_axes 메소드로 위치와 크기를 지정하여 axes 객체를 생성한다.
    ax1 = fig.add_axes([left, bottom, width, height])
    left, bottom : 상대적인 시작 위치 (figsize의 크기를 1이라고 했을 때 상대적 위치)
    width, height : 상대적인 크기(figsize의 크기를 1이라고 했을 때 상대적 크기)
  3. axes에 그래프를 그린다.
    ax1.plot(x,y)
  4. axes에 제목 추가.
    ax1.set_title(제목)

위치와 크기를 자유롭게 지정하여 axes 객체 만들기

  • add_axes를 사용하면, 서브플롯의 크기와 위치를 자유롭게 지정할 수 있다.
  • 그래프를 겹쳐그리거나, 크기가 각각 다른 그래프를 그릴 수 있다.

 

# 1)figure 객체를 생성한다.
fig = plt.figure(figsize=(8,6))

# 2) figure객체의 add_axes 메소드로 위치와 크기를 지정하여 axes 객체를 생성한다.
ax1 = fig.add_axes([0,0.5,0.4,0.4])
ax2 = fig.add_axes([0.5,0.5,0.4,0.4])
ax3 = fig.add_axes([0,0,0.4,0.4])
ax4 = fig.add_axes([0.5,0,0.4,0.4])

# 3) axes에 그래프를 그린다.
ax1.plot(df1['x'],df1['y'],'o')
ax2.plot(df2['x'],df2['y'],'r^')
ax3.plot(df3['x'],df3['y'],'k*')
ax4.plot(df4['x'],df4['y'],'m+')

# 4) axes에 제목 추가.
ax1.set_title('ax1')
ax2.set_title('ax2')
ax3.set_title('ax3')
ax4.set_title('ax4')

 

 

axes를 행, 열로 쪼개어 서브플롯 그리기

  • plt.subplots() 함수를 호출하면 figure, axes 객체를 생성하여 튜플 형태로 반환한다.
    fig, ax = plt.subplots()

  1. axes 객체를 행,열로 쪼개어 생성하기
    fig, ax = plt.subplots(nrows=행개수, ncols=열개수,figsize=(가로사이즈,세로사이즈))

  2. axes[행번호][열번호] 형태로 접근하여 그래프 그리기
  3. 서브플롯간 축을 공유할 수 있다.
    sharex=True, sharey=True

 

# 1) axes 객체를 행,열로 쪼개어 생성하기
# 3) 서브플롯간 축을 공유할 수 있다.
fig,ax = plt.subplots(nrows=2, ncols=2, figsize=(8,6), sharex=True, sharey=True)

# 2) axes[행번호][열번호] 형태로 접근하여 그래프 그리기
ax[0][0].plot(df1['x'],df1['y'],'o')
ax[0][1].plot(df2['x'],df2['y'],'^')
ax[1][0].plot(df3['x'],df3['y'],'*')
ax[1][1].plot(df4['x'],df4['y'],'d')

# 4) 각 그래프에 제목 추가
ax[0][0].set_title('ax1')
ax[0][1].set_title('ax2')
ax[1][0].set_title('ax3')
ax[1][1].set_title('ax4')

# 4) 각 그래프에 그리드 추가
ax[0][0].grid(ls=':')
ax[0][1].grid(ls=':', color='pink')
ax[1][0].grid(ls=':', color='skyblue')
ax[1][1].grid(ls=':', color='green', alpha=0.5)

# 6) 그래프 전체 제목
fig.suptitle('Anscombe', size=20)

# 7) 그래프 간격, 크기 최적화
fig.tight_layout()

 

 

 

전체 행 열과 그래프 순서에 따라 서브플롯 그리기

  1. figure 객체를 생성한다.
    fig=plt.figure()

  2. 서브플롯을 그릴 axes 객체를 생성한다.
    ax = fig.add_subplot(전체행개수,전체열개수,순서)

  1. axes 객체에 그래프를 그린다.
    ax.plot(x,y)
  2. 축 공유하기 : 어떤 axes의 축을 공유할 것인지 지정한다.
    sharex=axes객체, sharey=axes객체

 

# 1) figure 객체를 생성한다.
fig = plt.figure(figsize=(9,6), facecolor='ivory')

# 2) 서브플롯을 그릴 axes 객체를 생성한다.
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2, sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(2,2,3, sharex=ax1, sharey=ax1)
ax4 = fig.add_subplot(2,2,4)


# 3) axes 객체에 그래프를 그린다.
# 4) 축 공유하기 : 어떤 axes의 축을 공유할 것인지 지정한다.
ax1.plot(df1['x'],df1['y'],'o', label='ax1')
ax2.plot(df2['x'],df2['y'],'^', label='ax2')
ax3.plot(df3['x'],df3['y'],'*', label='ax3')
ax4.plot(df4['x'],df4['y'],'+', label='ax4')

# 4) 틱 변경하기
ax4.set_xticks(range(1,20,1))
ax4.set_yticks(range(1,15,1))

# 5) 범례 표시하기
ax1.legend(loc=2)
ax2.legend(loc=2)
ax3.legend(loc=2)
ax4.legend(loc=2)

# 6) figure 제목 추가하기
fig.suptitle('Anscombe', size=20)

# 8) 그래프 크기,간격 최적화하기
fig.tight_layout()

plt.show()

 

 

 

 

 

 

 

 

 

 

 

numpy 함수 응용

x = np.linspace(-4, 4,100) # [-4, 4] 범위에서 100개의 값 생성
y1 = x**3  
y2 = 10*x**2 - 2

plt.plot(x, y1, x, y2)
plt.show()

축의 범위 지정

  • plt.xlim(min,max)
  • plt.ylim(min,max)
plt.plot(x, y1, x, y2)
plt.xlim(-1, 1)
plt.ylim(-3, 3)
plt.show()

 

 

 

 

그래프 꾸미는 기호

 

기본 default 색

import numpy as np
x = np.arange(0, 5, 1)
y1 = x
y2 = x + 1
y3 = x + 2
y4 = x + 3

plt.plot(x, y1, x, y2, x, y3, x, y4)
plt.show()

 

 

색 지정하기      # 색상이름 약자(blue:b, green:g, red:r, cyan:c, magenta:m, yellow:y, black:k, white:w)

plt.plot(x, y1, 'm', x, y2,'y', x, y3, 'k', x, y4, 'c')
plt.show()

 

 

또는

plt.plot(x,y,color='skyblue')
plt.plot(x,y,color='#A566FF')  # 이런식으로 색 지정도 可

 

 

 

 

 

 

선 종류 지정하기

plt.plot(x, y1, '-', x, y2, '--', x, y3, ':',  x, y4, '-.')
plt.show()

 

 

점 모양 (marker) 지정하기

plt.plot(x, y1, 'o', x, y2, '^',x, y3, 's', x, y4, 'd')
plt.show()

 

  • marker : 마커종류 (* . , o v ^ < > 1 2 3 4 s p * h H + x D d)
  • markersize, ms : 마커사이즈
  • markeredgecolor, mec : 마커 선 색깔
  • markeredgewidth, mew : 마커 선 굵기
  • markerfacecolor, mfc : 마커 내부 색깔

총 정리

plt.plot(x,y,color='#A566FF', marker='D', ms='10', mec='b', mew='3', mfc='y')

 

 

 

점 모양 선 연결하기

plt.plot(x, y1, '>--r', x, y2, 's-g', x, y3, 'd:b', x, y4, '-.Xc')
plt.show()

 

선 종류 총 정리

  • linestyle, ls : 선스타일
    '-' solid line style
    '--' dashed line style
    '-.' dash-dot line style
    ':' dotted line style
  • linewidth, lw : 선 굵기
plt.plot(x,y,color='#A566FF', marker='D', ms='10', mec='b', mew='3', mfc='y', ls=':', lw=3)

 

솔직히 이런 꾸밈 기호는 다 기억하기 어려우니 라이브러리나 구글링을 참조하자. (또는 ipynb파일 참조)

 

 

 

그래프에 이름 붙이는 label, title 함수

  • plt.grid(True)
  • axis : 그리드 방향
  • ls, lw, color, alpha 등의 속성을 지정할 수 있음
import numpy as np

x = np.arange(-4.5, 5, 0.5)
y = 2*x**3


plt.plot(x,y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Graph title')
plt.show()

 

격자 무늬 추가해서 보여주는 grid 함수

plt.plot(x,y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Graph title')
plt.grid(True) # 'plt.grid()'도 가능

 

 

 

범례 추가하는 legend 함수

import numpy as np
x = np.arange(0, 5, 1)
y1 = x
y2 = x + 1
y3 = x + 2
y4 = x + 3

plt.plot(x, y1, '>--r', x, y2, 's-g', x, y3, 'd:b', x, y4, '-.Xc')
plt.legend(['data1', 'data2', 'data3', 'data4'])
plt.show()

 

한글폰트, 마이너스기호 깨짐 방지 설정

matplotlib.rcParams['font.family'] = 'Malgun Gothic'   # '맑은 고딕' 폰트 지정
matplotlib.rcParams['axes.unicode_minus'] = False  # 한글폰트, 마이너스 기호 깨짐 방지 설정

 

 

범례 위치 조정하는 loc(location) 설정

plt.plot(x, y1, '>--r', x, y2, 's-g', x, y3, 'd:b', x, y4, '-.Xc')
plt.legend(['data1', 'data2', 'data3', 'data4'], loc = 4)   # loc = 4 는 4분면 의미. 
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Graph title')
plt.grid(True)

 

plt.legend(['data1', 'data2', 'data3', 'data4'], loc = 'lower right')
# 4분면 대신에 이런식의 위치 지정도 可. loc='best' 입력시 최적 위치 자동 설정.

 

 

틱(tick) 지정   = x축, y축 눈금을 의미

  • plt.xticks(틱리스트)  ->  plt.xticks(눈금리스트, label = 레이블리스트)
  • plt.yticks(틱리스트)  ->  plt.yticks(눈금리스트, label = 레이블리스트)
  • 눈금의 개수와 동일한 개수의 레이블을 지정한다.

틱 스타일

  • plt.tick_params( )
  • direction : 틱 위치 (in, out, inout)
  • length : 틱의 길이
  • width : 틱의 두께
  • color : 틱 색상
  • labelcolor : 틱 레이블 색상
  • colors : 틱과 틱 레이블 색상
  • pad : 틱과 레이블 사이의 거리
  • labelsize : 틱 레이블 사이즈
  • axis : 축 지정
# x축 : 0,1,2,3,4,5,6,7,8,9,10,11,12,13
# y축 : 0,10,20,30,40,50,60,70,80,90,100

xticks_lable = ['','1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월','']
yticks_lable = ['0kg','10kg','20kg','30kg','40kg','50kg','60kg','70kg','80kg','90kg','100kg']

# x축 : 0,1,2,3,4,5,6,7,8,9,10,11,12,13
# y축 : 0,10,20,30,40,50,60,70,80,90,100

x = df['월']
y = df['몸무게']
plt.plot(x,y,'bo-', mfc='r',mec='r')

# title
plt.title('월별 몸무게 변화', size=15, color='b', fontweight='bold')

# 축 레이블
plt.xlabel('월')
plt.ylabel('몸무게(kg)')

# 틱
plt.xticks(range(0,14,1), labels=xticks_lable)
plt.yticks(range(0,110,10), labels=yticks_lable)

#plt.tick_params(direction='inout',length=10,width=2,color='g',labelcolor='m' )
plt.tick_params(axis='x',direction='inout',length=10,width=2,colors='g',labelsize=12 )
plt.tick_params(axis='y',direction='inout',length=10,width=2,colors='b',labelsize=12 )
# 그리드
plt.grid(ls=':')
plt.show()

 

 

 

 

 

 

 

좌표에 따른 문자열 출력하기

plt.plot(x, y1, '>--r', x, y2, 's-g', x, y3, 'd:b', x, y4, '-.Xc')
plt.text(0, 6, "문자열 출력 1")
plt.text(0, 5, "문자열 출력 2")
plt.text(3, 1, "문자열 출력 3")
plt.text(3, 0, "문자열 출력 4")
plt.show()

  • plt.xlabel('레이블')
  • plt.ylabel('레이블')
  • loc : 위치('left','center','right' / 'bottom', 'center','top')
  • labelpad : 레이블과 그래프와의 간격
  • color : 폰트색상
  • fontsize : 폰트사이즈
  • fontfamily : 폰트

 

 

 

 

응용예제

x = df['월']
y = df['몸무게']
plt.plot(x,y,'ro-', mec='b', mfc='b', lw=3, ms=7)
plt.title('월별 몸무게 변화', loc='center', pad=10, color='r', fontsize=20, fontweight='bold'
          , fontfamily='Nanum Pen Script')

plt.xlabel('월',loc='right',labelpad=10, color='b',fontsize=12)
plt.ylabel('몸무게(kg)', loc='top',labelpad=10, color='b', fontsize=12)
plt.show()

 

 

 

 

 

산점도 점크기 조절하기

import matplotlib.pyplot as plt

height = [165, 177, 160, 180, 185, 155, 172]   # 키 데이터
weight = [62, 67, 55, 74, 90, 43, 64]   # 몸무게 데이터
plt.scatter(height, weight, s=500, c='r') # 마커 크기는 500, 컬러는 붉은색(red)
plt.show()

 

경우에 따라 색깔과 크기 지정하기 (리스트 또는 함수 활용)

size = 100 * np.arange(1,8) # 데이터별로 마커의 크기 지정
colors = ['r', 'g', 'b', 'c', 'm', 'k', 'y'] # 데이터별로 마커의 컬러 지정

plt.scatter(height, weight, s=size, c=colors)
plt.show()

 

 

 

 

복잡한 활용 예제

import numpy as np

city = ['서울', '인천', '대전', '대구', '울산', '부산', '광주']

# 위도(latitude)와 경도(longitude)
lat  = [37.56, 37.45, 36.35, 35.87, 35.53, 35.18, 35.16] 
lon = [126.97, 126.70, 127.38, 128.60, 129.31, 129.07, 126.85]

# 인구 밀도(명/km^2): 2017년 통계청 자료
pop_den = [16154, 2751, 2839, 2790, 1099, 4454, 2995]

size = np.array(pop_den) * 0.2 # 마커의 크기 지정 
colors = ['r', 'g', 'b', 'c', 'm', 'k', 'y'] # 마커의 컬러 지정

plt.scatter(lon, lat, s=size, c=colors, alpha=0.5)
# alpha는 투명도 조절 옵션이다. alpha = 0 완전 투명  <-> alpha = 1 완전 불투명
plt.xlabel('경도(longitude)')
plt.ylabel('위도(latitude)')
plt.title('지역별 인구 밀도(2017)')

for x, y, name in zip(lon, lat, city):
    plt.text(x, y, name) # 위도 경도에 맞게 도시 이름 출력

plt.show()

 

 

컬러맵 색상지정

plt.scatter(x,y,c=y, cmap='cool')
plt.colorbar()

 

[참고!] 컬러맵 종류

plt.colormaps()

['Accent',
 'Accent_r',
 'Blues',
 'Blues_r',
 'BrBG',
 'BrBG_r',
 'BuGn',
 'BuGn_r',
 'BuPu',
 'BuPu_r',
 'CMRmap',
 'CMRmap_r',
 'Dark2',
 'Dark2_r',
 'GnBu',
 'GnBu_r',

.

.

.

(엄청 많음)

 

 

 

 

막대그래프

import matplotlib.pyplot as plt
import numpy as np

member_IDs = ['m_01', 'm_02', 'm_03', 'm_04'] # 회원 ID
before_ex = [27, 35, 40, 33] # 운동 시작 전
after_ex = [30, 38, 42, 37] # 운동 한 달 후

n_data = len(member_IDs)     # 회원이 네 명이므로 전체 데이터 수는 4
index = np.arange(n_data)   # NumPy를 이용해 배열 생성 (0, 1, 2, 3)
plt.bar(index, before_ex, tick_label = member_IDs)
# bar(x,y)에서 x=index, height(y) =before_ex 로 지정, label 지정
plt.show()

색 입히기

colors=['r', 'g', 'b', 'm']
plt.bar(index, before_ex, color = colors, tick_label = member_IDs) #color 추가
plt.show()

 

 

 

너비 조정 width = 옵션

plt.bar(index, before_ex, tick_label = member_IDs, width = 0.6)
plt.show()

 

 

 

 

막대 방향 전환하기 barh  instead of bar

colors=['r', 'g', 'b', 'm']
plt.barh(index, before_ex, color = colors, tick_label = member_IDs)
plt.show()

 

 

 

막대 테두리

  • edgecolor = 테두리 색상
  • linewidth = 테두리 두께
plt.bar(df1['요일'],df1['매출액'], width=0.4, color=['r','orange','y','g','b','navy','violet']
       ,edgecolor='gray',linewidth=2)

 

 

막대 패턴 지정

  • hatch 파라미터에 기호 전달 : '/', '', '|', '-', '+', 'x', 'o', 'O', '.', '*'
plt.bar(df1['요일'],df1['매출액'], width=0.4, color=['r','orange','y','g','b','navy','violet']
       ,edgecolor='gray',linewidth=2,hatch='x')

 

x하나 더 입력시 밀도가 진해진다.

plt.bar(df1['요일'],df1['매출액'], width=0.4, color=['r','orange','y','g','b','navy','violet']
       ,edgecolor='gray',linewidth=2,hatch='xx')

 

 

그외 다양한 패턴들(막대마다 다르게)

bars = plt.bar(df1['요일'],df1['매출액'], width=0.4, 
       color=['r','orange','y','g','b','navy','violet'], edgecolor='gray',linewidth=2)

bars[0].set_hatch('.')
bars[1].set_hatch('/')
bars[2].set_hatch('+')
bars[3].set_hatch('-')
bars[4].set_hatch('*')
bars[5].set_hatch('|')
bars[6].set_hatch('o')

 

꾸미기 예제

plt.bar(df1['요일'],df1['매출액'], hatch='/')
plt.title('요일별 매출액')
plt.xlabel('요일')
plt.ylabel('매출액(만원)')
plt.show()

 

 

 

 

 

두 개를 한번에 그리기: 그냥 bar 두개 설정하고 plot

두 막대그래프 붙여서 응용

barWidth = 0.4
plt.bar(index, before_ex, color='c', align='edge', width = barWidth, label='before')
plt.bar(index + barWidth, after_ex , color='m', align='edge', width = barWidth, label='after')

plt.xticks(index + barWidth, member_IDs)
plt.legend()
plt.xlabel('회원 ID')
plt.ylabel('윗몸일으키기 횟수')
plt.title('운동 시작 전과 후의 근지구력(복근) 변화 비교')
plt.show()

 

 

 

 

히스토그램 hist

math = [76, 82, 84, 83, 90, 86, 85, 92, 72, 71, 100, 87, 81, 76, 94, 78, 81, 60, 79, 69, 74, 87, 82, 68, 79]
plt.hist(math, bins= 8)  # bins: 몇칸으로 나눠서 출력할지 정의
plt.show()

 

grid와 label 적용

plt.hist(math, bins= 8)
plt.xlabel('시험 점수')
plt.ylabel('도수(frequency)')
plt.title('수학 시험의 히스토그램')
plt.grid()
plt.show()

 

 

 

 

 

원 그래프 pie()

fruit = ['사과', '바나나', '딸기', '오렌지', '포도']
result = [7, 6, 3, 2, 2]

plt.figure(figsize=(5,5))  # figszie: 출력 사이즈 가로 세로 5,5 로 설정
plt.pie(result, labels= fruit, autopct='%.1f%%')   # autopct로 출력양식 설정
plt.show()

plt.figure(figsize=(5,5))
plt.pie(result, labels= fruit, autopct='%.1f%%', startangle=90, counterclock = False)
plt.show()  # startangle: 시작 각도.  counterclock: 반시계 방향 설정

 

shadow 삽입.  explode value: 가장 큰 부분 분리 강조 여부

explode_value = (0.1, 0, 0, 0, 0)

plt.figure(figsize=(5,5))
plt.pie(result, labels= fruit, autopct='%.1f%%', startangle=90, counterclock = False, explode=explode_value, shadow=True)
plt.show()

 

 

 

savefig로 파일 저장하기

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 1)
y1 = x
y2 = x + 1
y3 = x + 2
y4 = x + 3

plt.plot(x, y1, x, y2, x, y3, x, y4)

plt.grid(True)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Saving a figure')

# 그래프를 이미지 파일로 저장. dpi(해상도)는 100으로 설정
plt.savefig('C:/myPyCode/figures/saveFigTest1.png', dpi = 100) 
plt.show()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

boxplot()

import numpy as np
data = np.random.randint(1,101,1000)  # 샘플데이터 (1~100사이의 랜덤 정수 1000개)
data

plt.boxplot(data)
plt.show()

plt.boxplot(scores)
plt.title('성적 분포')
plt.ylabel('점수')
plt.show()

 

Violinplot

plt.violinplot(data)
plt.show()

산점도 관계설정

 

import seaborn as sns    ## 샘플데이터 (지불금액에 따른 팁)
tips = sns.load_dataset('tips')[['total_bill','tip']]
plt.scatter(tips['total_bill'], tips['tip'])

plot(x, y)   bar(x, y) 도 이와 같이 적용.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

pandas로 그래프 그리는 방법도 있지만 주로 mlt 패키지를쓰지 굳이 판다스로 쓰지 않는다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

detail 작업을 위해 다음 패키지를 사용하기도 한다.

import seaborn as sns

더 이쁘게 그릴 수는 있지만 다양성이 약하다고 함

seaborn 공부자료 참고

 

 

그외 각종 라이브러리들이 많다. 필요할 때에 맞춰 패키지를 구글링하여 참조하자.

728x90
반응형