© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🕕
Visualization 목차
Matplotlib 데이터를 Chart, Plot으로 시각화해주는 라이브러리이다. 기본 구성 : 그림(figure), 축(axes) % matplotlib inline : jupyter notebook 내에서 output을 보여준다.
Basic Attributes kind : line, bar, barh, kde xlim, ylim : X축과 Y축의 경계(axis로 한번에 그릴 수 있음) grid : 그리드 표현(True, False) linestyle : 실선, 점선, 1점 쇄선 등
Line Plot Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
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
Out[-]
Scatter Plot Out[-]
histogram 막대그래프는 계급 즉 가로를 생각하지 않고 세로의 높이로만 나타낸다. (출처 : 위키백과) 연속형 자료를 계급으로 나누어 계급별 도수를 막대로 나타낸다. Out[-]
Pie Chart Out[-]
Out[-]
Out[-]
Bar Chart Out[-]
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') -> 빨간색 파선 'o' circle marker(plt.plot(x, y_, '-o'))
Plotly 웹 시각화인 자바스크립트의 라이브러리 D3를 이용해 그래프가 웹에서 빠르게 그려진다. Line Plot Out[-]
Out[-]
Bar Chart Out[-]
Scatter Plot Out[-]
Pie Chart Out[-]
Out[-]
이미지 분석 이미지는 작은 사각형 모양의 픽셀을 모아서 구성되어있다. 이미지 크기는 (세로픽셀수X가로픽셀수)로 표현한다. 이미지를 저장할 때는 색을 표현하는 스칼라 값이나 2차원 vector로 표현한다. RGB는 색공간을 말한다. Red, Green, Blue로 세개가 합쳐진 벡터이다.
skimage(scikit-image) : 이미지 처리를 위한 파이썬 라이브러리이다. numpy array로 동작한다.
PIL(Python Image Library) cv2 : OpenCV는 Open Source Computer Vision Library의 약자로 오픈소스 컴퓨터 비전 및 머신러닝 라이브러리이다. 이 라이브러리를 불러올 때는 cv2를 사용한다.
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
Out[-]
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = [100, 200, 300]
y = [1, 2, 3]
plt.plot(x, y)
x = [100, 200, 300]
y = [1, 2, 3]
# y 먼저 입력
value = pd.Series([1, 2, 3], [100, 200, 300])
plt.plot(value)
x = [100, 200, 300]
y = [1, 2, 3]
plt.plot(x, y, ':r') # red색 점선
x = [100, 200, 300]
y = [1, 2, 3]
plt.plot(x, y, color='#ff0000', linewidth=10) # 16진수 색상 값 (RGB) , 선두께
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축 이름
# 이미지 저장하기
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')
# 두개 그래프 동시에 그리기
x = np.linspace(0, 10, 100)
y = np.sin(x)
y_ = np.cos(x)
plt.plot(x, y)
plt.plot(x, y_, '-o') # -o 모양으로 그리기
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)
x = np.linspace(0, 10, 20)
y = x ** 2
plt.scatter(x, y, color='r', alpha=0.5)
plt.show()
# 우상향 그래프로 x,y 두 변수는 양의 상관관계임을 나타낸다.
x = [np.random.randint(1, 7) for i in range(100000)]
plt.hist(x, bins=11)
plt.show()
labels = ['one', 'two', 'three']
size = [100, 20, 10]
plt.pie(size, labels=labels)
plt.show()
labels = ['one', 'two', 'three']
size = [100, 20, 10]
plt.pie(size, labels=labels, shadow=True) # 그림자 넣기
plt.show()
labels = ['one', 'two', 'three']
size = [50, 20, 30]
plt.pie(size, labels = labels, shadow = True, autopct = '%1.2f%%') # 자동 비율 추가하기
plt.show()
plt.bar(['one', 'two', 'three'], [10, 20, 30])
plt.show()
plt.barh(['one', 'two', 'three'], [10, 20, 30]) # 가로방향 그래프
plt.show()
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()
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()
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
# 한국 GDP 데이터 셋
korea_gdp = px.data.gapminder().query("country == 'Korea, Rep.'")
fig = px.bar(korea_gdp, x='year', y='gdpPercap', title = "한국인 GDP")
fig.show()
# 한국 기대 수명과 GDP의 상관관계
korea_data = px.data.gapminder().query("country == 'Korea, Rep.'")
fig = px.scatter(korea_data, x = 'gdpPercap', y = 'lifeExp')
fig.show()
fig = px.pie(values = [20, 30, 50])
fig.show()
labels = ['one', 'two', 'three']
values = [20, 30, 50]
fig =go.Figure(data = [go.Pie(values = values, labels = labels)]) # 범례 추가하기
fig.show()
import numpy as np
from skimage import io
# from PIL import Image
# from cv2
import matplotlib.pyplot as plt
jeju = io.imread('jeju.jpg') # 이미지 불러오기
Out[-]
imageio.core.util.Array
Out[-]
(960, 1280, 3) # 세로, 가로, RGB(색)
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)
plt.imshow(jeju[::-1]) # 상하로 뒤집기
plt.imshow(jeju[:, ::-1]) # 좌우로 뒤집기
plt.imshow(jeju[::-1, :])
plt.imshow(jeju[550:800, :]) # 부분만 잘라내기
plt.imshow(jeju[550:800, 500:720])
plt.imshow(jeju[::3, ::3]) # 3칸씩 건너 뛰기
plt.imshow(jeju[::6, ::6]) # 6칸씩 건너 뛰기 : 화질이 깨진 것을 볼 수 있다
plt.imshow(jeju[::10, ::10]) # 10칸씩 건너 뛰기 : 화질이 많이 깨짐
miniJeju = jeju[::10, ::10]
# 색 정보를 일렬로 나열하고 어디에 많이 분포 되었는 지를 확인한다.
plt.hist(miniJeju.ravel(), 256, [0, 256])
plt.show()
# 특정한 값(50)을 지정하고 그 이하는 원래의 색으로 나오고 다른 값은 검정색(0)으로 지정하여
# 이미지를 출력한다.
miniJeju_ = np.where(miniJeju < 50, miniJeju, 0)
plt.imshow(miniJeju_)
plt.imshow(jeju[:, :, 0]) # 0번째 색만 출력하기
plt.imshow(jeju[:, :, 1]) # 1번째 색만 출력하기
plt.imshow(jeju[:, :, 2]) # 2번째 색만 출력하기
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)
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)