
목차
목차MatplotlibBasic AttributesLine Plotlabel legend Scatter PlothistogramPie ChartBar Chart선 색상과 스타일PlotlyLine PlotBar ChartScatter PlotPie Chart이미지 분석
Matplotlib
- 데이터를 Chart, Plot으로 시각화해주는 라이브러리이다.
- 2003년 0.1 출시, 17년이된 패키지
- 가장 많이 사용되는 시각화 패키지이다.
- 기본 구성 : 그림(figure), 축(axes)
- % matplotlib inline : jupyter notebook 내에서 output을 보여준다.
Basic Attributes
- alpha : 투명도
- logy : Y축 Log scaling
- kind : line, bar, barh, kde
- subplots : 여러개의 plot 그리기
- legend : subplot의 범례 지정
- xlim, ylim : X축과 Y축의 경계(axis로 한번에 그릴 수 있음)
- grid : 그리드 표현(True, False)
- title : 그래프의 제목 지정
- linewidth : 라인 넓이
- color : 색
- linestyle : 실선, 점선, 1점 쇄선 등
- marker : 마커 지정
- markerfacecolor : 마커 색
- markersize : 마커 크기
- 그 외 Attribute : https://matplotlib.org/3.1.1/tutorials/introductory/pyplot.html
Line Plot
import numpy as np import pandas as pd import matplotlib.pyplot as plt
%matplotlib inline
x = [100, 200, 300] y = [1, 2, 3] plt.plot(x, y)
Out[-]

x = [100, 200, 300] y = [1, 2, 3] # y 먼저 입력 value = pd.Series([1, 2, 3], [100, 200, 300]) plt.plot(value)
Out[-]

x = [100, 200, 300] y = [1, 2, 3] plt.plot(x, y, ':r') # red색 점선
Out[-]

x = [100, 200, 300] y = [1, 2, 3] plt.plot(x, y, color='#ff0000', linewidth=10) # 16진수 색상 값 (RGB) , 선두께
Out[-]

x = [100, 200, 300] y = [1, 2, 3] plt.plot(x, y, color='#ff0000', linewidth=10) plt.title('hello world', fontsize=20) # 제목 plt.xlabel('hello', fontsize=10) # x축 이름 plt.ylabel(' world', fontsize=10) # y축 이름
Out[-]
Text(0, 0.5, ' world')

# 이미지 저장하기 x = [100, 200, 300] y = [1, 2, 3] plt.plot(x, y, color='#ff0000', linewidth=10) plt.title('hello world', fontsize=20) plt.xlabel('hello', fontsize=10) plt.ylabel(' world', fontsize=10) plt.savefig('sample.png')
Out[-]

# 두개 그래프 동시에 그리기 x = np.linspace(0, 10, 100) y = np.sin(x) y_ = np.cos(x) plt.plot(x, y) plt.plot(x, y_, '-o') # -o 모양으로 그리기
Out[-]

label
- 무슨 데이터인지 표시해주는 방법
legend
- 좌표축에 범례를 추가해주는 방법
- loc : legend 위치
- 'best' 0
- 'upper right' 1
- 'upper left' 2
- 'lower left' 3
- 'lower right' 4
- 'right' 5
- 'center left' 6
- 'center right' 7
- 'lower center' 8
- 'upper center' 9
- 'center' 10
x = np.linspace(0, 10, 100) y = np.sin(x) y_ = np.cos(x) # 범례 추가하기 plt.plot(x, y, label='sin') plt.plot(x, y_, '-o', label='cos') # 4번 위치에 범례 넣기 plt.legend(loc=4)
Out[-]

Scatter Plot
- 변수들의 상관관계, 밀집 위치를 나타낸다.
x = np.linspace(0, 10, 20) y = x ** 2 plt.scatter(x, y, color='r', alpha=0.5) plt.show() # 우상향 그래프로 x,y 두 변수는 양의 상관관계임을 나타낸다.
Out[-]

histogram
- 도수분포표를 그래프로 나타낸 방법이다.
- 막대그래프는 계급 즉 가로를 생각하지 않고 세로의 높이로만 나타낸다. (출처 : 위키백과)
- 연속형 자료를 계급으로 나누어 계급별 도수를 막대로 나타낸다.
x = [np.random.randint(1, 7) for i in range(100000)]
plt.hist(x, bins=11) plt.show()
Out[-]

Pie Chart
labels = ['one', 'two', 'three'] size = [100, 20, 10] plt.pie(size, labels=labels) plt.show()
Out[-]

labels = ['one', 'two', 'three'] size = [100, 20, 10] plt.pie(size, labels=labels, shadow=True) # 그림자 넣기 plt.show()
Out[-]

labels = ['one', 'two', 'three'] size = [50, 20, 30] plt.pie(size, labels = labels, shadow = True, autopct = '%1.2f%%') # 자동 비율 추가하기 plt.show()
Out[-]

Bar Chart
- 범주형 자료의 분포를 파악한다.
plt.bar(['one', 'two', 'three'], [10, 20, 30]) plt.show()
Out[-]

plt.barh(['one', 'two', 'three'], [10, 20, 30]) # 가로방향 그래프 plt.show()
Out[-]

선 색상과 스타일
- plt.plot(x, y, color='red') -> red, green, blue 등 색상 이름
- plt.plot(x, y, color='r') -> r, g, b, y, m(자홍), k(검정) 등 색상 이름
- plt.plot(x, y, color='0.2') -> 회색조(0-1사이 값)
- plt.plot(x, y, color='#ff0000') -> 16진수 색상 값
- plt.plot(x, y, linestyle='solid') -> 실선('-')
- plt.plot(x, y, linestyle='dashed') -> 파선('--')
- plt.plot(x, y, linestyle='dashdot') -> 1점 쇄선('-.')
- plt.plot(x, y, linestyle='dotted') -> 점선(':')
- plt.plot(x, y, '--r') -> 빨간색 파선
- '.' point marker
- 'o' circle marker(plt.plot(x, y_, '-o'))
- '^' triangle_up marker
- 's' square marker
- 'p' pentagon marker
- '*' star marker
- '+' plus marker
- 'x' x marker
Plotly
- 인터랙티브한 그래프를 그리기에 적합한 패키지
- 웹 시각화인 자바스크립트의 라이브러리 D3를 이용해 그래프가 웹에서 빠르게 그려진다.
- 공식홈페이지(https://plotly.com/python/) 튜토리얼
Line Plot
import plotly.express as px x_ = np.array([1, 2, 3, 4, 5]) y_ = x_ ** 2 fig = px.line(x=x_, y=y_) fig.show()
Out[-]
.png?table=block&id=7e6a0149-89a9-4458-ac96-75b725dc2e76&cache=v2)
import plotly.express as px import plotly.graph_objects as go # gapminder 데이터 셋 사용하기 korea_life = px.data.gapminder().query("country == 'Korea, Rep.'") # 한국인 기대 수명 fig = px.line(korea_life, x="year", y="lifeExp", title='Life expectancy in Korea') fig.show()
Out[-]
.png?table=block&id=78b96e1a-8fd9-4f2b-8500-6bdea529a9ee&cache=v2)
korea_life["year"] korea_life["lifeExp"]
Out[-] 840 47.453 841 52.681 842 55.292 843 57.716 844 62.612 845 64.766 846 67.123 847 69.810 848 72.244 849 74.647 850 77.045 851 78.623 Name: lifeExp, dtype: float64
Bar Chart
# 한국 GDP 데이터 셋 korea_gdp = px.data.gapminder().query("country == 'Korea, Rep.'") fig = px.bar(korea_gdp, x='year', y='gdpPercap', title = "한국인 GDP") fig.show()
Out[-]
.png?table=block&id=e673d6bd-fd1c-4204-9151-643f8f984490&cache=v2)
Scatter Plot
# 한국 기대 수명과 GDP의 상관관계 korea_data = px.data.gapminder().query("country == 'Korea, Rep.'") fig = px.scatter(korea_data, x = 'gdpPercap', y = 'lifeExp') fig.show()
Out[-]
.png?table=block&id=576f74f2-7c82-478e-b604-79af2e04efa2&cache=v2)
Pie Chart
fig = px.pie(values = [20, 30, 50]) fig.show()
Out[-]
.png?table=block&id=037d94e9-bf48-43c1-b247-8847facb4d6c&cache=v2)
labels = ['one', 'two', 'three'] values = [20, 30, 50] fig =go.Figure(data = [go.Pie(values = values, labels = labels)]) # 범례 추가하기 fig.show()
Out[-]
.png?table=block&id=dca7f994-5c6b-4433-89af-4974160178ed&cache=v2)
이미지 분석
- 이미지는 작은 사각형 모양의 픽셀을 모아서 구성되어있다.
- 이미지 크기는 (세로픽셀수X가로픽셀수)로 표현한다.
- 이미지를 저장할 때는 색을 표현하는 스칼라 값이나 2차원 vector로 표현한다.
- RGB는 색공간을 말한다. Red, Green, Blue로 세개가 합쳐진 벡터이다.
- skimage(scikit-image) : 이미지 처리를 위한 파이썬 라이브러리이다. numpy array로 동작한다.
- PIL(Python Image Library)
- Pillow : 이미지 처리와 그래픽 기능을 제공하는 파이썬 라이브러리이다.
(더이상 PIL은 지원하지 않고 그 후속 프로젝트인 Pillow를 사용한다)
- cv2 : OpenCV는 Open Source Computer Vision Library의 약자로 오픈소스 컴퓨터 비전 및 머신러닝 라이브러리이다. 이 라이브러리를 불러올 때는 cv2를 사용한다.
import numpy as np from skimage import io # from PIL import Image # from cv2 import matplotlib.pyplot as plt
jeju = io.imread('jeju.jpg') # 이미지 불러오기
type(jeju) # 이미지 타입 확인하기
Out[-] imageio.core.util.Array
jeju.shape
Out[-] (960, 1280, 3) # 세로, 가로, RGB(색)
jeju
Out[-] Array([[[171, 222, 251], [172, 223, 252], [172, 223, 252], ..., [124, 189, 255], [121, 189, 254], [120, 188, 253]], [[173, 224, 253], [173, 224, 253], [173, 224, 253], ..., [124, 189, 255], [122, 190, 255], [121, 189, 254]], [[174, 225, 254], [174, 225, 254], [175, 226, 255] ..., [125, 190, 255], [122, 190, 255], [122, 190, 255]], ..., [[ 66, 93, 26], [ 89, 114, 46], [ 49, 72, 2], ..., [ 2, 29, 0], [ 34, 59, 17], [ 40, 63, 21]], [[ 44, 71, 4], [ 23, 50, 0], [ 29, 52, 0], ..., [ 40, 67, 22], [ 0, 19, 0], [ 16, 41, 0]], [[ 29, 58, 0], [ 44, 71, 2], [ 84, 110, 37], ..., [ 17, 44, 1], [ 33, 60, 17], [ 18, 43, 1]]], dtype=uint8)
np.min(jeju), np.max(jeju)
Out[-] (0, 255)
plt.imshow(jeju)
Out[-]

plt.imshow(jeju[::-1]) # 상하로 뒤집기
Out[-]

plt.imshow(jeju[:, ::-1]) # 좌우로 뒤집기
Out[-]

plt.imshow(jeju[::-1, :])
Out[-]

plt.imshow(jeju[550:800, :]) # 부분만 잘라내기
Out[-]

plt.imshow(jeju[550:800, 500:720])
Out[-]

plt.imshow(jeju[::3, ::3]) # 3칸씩 건너 뛰기
Out[-]

plt.imshow(jeju[::6, ::6]) # 6칸씩 건너 뛰기 : 화질이 깨진 것을 볼 수 있다
Out[-]

plt.imshow(jeju[::10, ::10]) # 10칸씩 건너 뛰기 : 화질이 많이 깨짐
Out[-]

miniJeju = jeju[::10, ::10]
# 색 정보를 일렬로 나열하고 어디에 많이 분포 되었는 지를 확인한다. plt.hist(miniJeju.ravel(), 256, [0, 256]) plt.show()
Out[-]

# 특정한 값(50)을 지정하고 그 이하는 원래의 색으로 나오고 다른 값은 검정색(0)으로 지정하여 # 이미지를 출력한다. miniJeju_ = np.where(miniJeju < 50, miniJeju, 0) plt.imshow(miniJeju_)
Out[-]

plt.imshow(jeju[:, :, 0]) # 0번째 색만 출력하기
Out[-]

plt.imshow(jeju[:, :, 1]) # 1번째 색만 출력하기
Out[-]

plt.imshow(jeju[:, :, 2]) # 2번째 색만 출력하기
Out[-]

jeju[:, :, 0] # 0번째 색 정보 출력
Out[-] Array([[171, 172, 172, ..., 124, 121, 120], [173, 173, 173, ..., 124, 122, 121], [174, 174, 175, ..., 125, 122, 122], ..., [ 66, 89, 49, ..., 2, 34, 40], [ 44, 23, 29, ..., 40, 0, 16], [ 29, 44, 84, ..., 17, 33, 18]], dtype=uint8)
jeju[:, :]
Out[-] Array([[[171, 222, 251], [172, 223, 252], [172, 223, 252], ..., [124, 189, 255], [121, 189, 254], [120, 188, 253]], [[173, 224, 253], [173, 224, 253], [173, 224, 253], ..., [124, 189, 255], [122, 190, 255], [121, 189, 254]], [[174, 225, 254], [174, 225, 254], [175, 226, 255], ..., [125, 190, 255], [122, 190, 255], [122, 190, 255]], ..., [[ 66, 93, 26], [ 89, 114, 46], [ 49, 72, 2], ..., [ 2, 29, 0], [ 34, 59, 17], [ 40, 63, 21]], [[ 44, 71, 4], [ 23, 50, 0], [ 29, 52, 0], ..., [ 40, 67, 22], [ 0, 19, 0], [ 16, 41, 0]], [[ 29, 58, 0], [ 44, 71, 2], [ 84, 110, 37], ..., [ 17, 44, 1], [ 33, 60, 17], [ 18, 43, 1]]], dtype=uint8)
# 회색으로 이미지 출력하기 from skimage import color plt.imshow(color.rgb2gray(jeju), cmap=plt.cm.gray)
Out[-]
