Seaborn은 Matplotlib의 기능과 스타일을 확장한 파이썬 시각화 도구의 고급버전이지만 쉽다.

# import library
import seaborn as sns

# 타이타닉 데이터셋 로딩
titan_df = sns.load_dataset('titanic')

 

회귀직선이 있는 산점도

import matplotlib.pyplot as plt
import seaborn as sns

# 스타일을 지정 - darkgrid
sns.set_style('darkgrid')
# 그래프 객체 생성 - 한 out에 그래프를 살펴보도록
fig = plt.figure(figsize=(15,5)) # 15: 가로길이 // 5: 세로길이
ax1 = fig.add_subplot(1,2,1)  # 1 x 2 사이즈에서 1번째 (왼쪽에 위치함)
ax2 = fig.add_subplot(1,2,2)  # 1 x 2 사이즈에서 2번째 (오른쪽에 위치함)

# 그래프 그리기 - 선형회귀선 표시 (fit_reg = True)
sns.regplot(x='age', y='fare',
           data=titan_df,
           ax=ax1)


# 그래프 그리기 - 선형회귀선 미표시 (fit_reg = false)
sns.regplot(x='age', y='fare',
           data=titan_df,
           ax=ax2,
           fit_reg=False)

plt.show()

 

히스토그램 및 밀도함수

 

# 그래프 객체 생성 - 한 out에 그래프를 살펴보도록
fig = plt.figure(figsize=(15,5)) # 15,5 // 16,8
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)

# 기본값 
sns.distplot(titan_df.fare, ax=ax1)

# hist = False
sns.distplot(titan_df.fare, hist=False, ax=ax2)

# kde = False
sns.distplot(titan_df.fare, kde=False, ax=ax3) # Kernel Density 

# 차트 제목 표시
ax1.set_title('titan fare-hist/kde')
ax2.set_title('titan fare-hist')
ax3.set_title('titan fare-kde')

plt.show()

 

 

히트맵(Heat-map)

# 테이블 생성
table = titan_df.pivot_table(index=['sex'], columns=['class'], aggfunc='size')

# 히트맵 그리기
sns.heatmap(table,
           annot=True,
           fmt='d',
           linewidth=1) # heat-map을 쓰실때 cmap - color mapping :: heatmap_cmap의 종류

박스플롯 / 바이올린 플롯

import matplotlib.pyplot as plt
import seaborn as sns

# 데이터 로드
titan_df = sns.load_dataset('titanic')

# set_style theme
sns.set_style('whitegrid')

# 그래프 객체 생성
fig = plt.figure(figsize=(15,5))
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)

# 박스플롯 - 기본값
sns.boxplot(x='alive', y='age', data=titan_df, ax=ax1).set(title='BOXPLOT')
      # .set(title='BOXPLOT') 타이틀 넣어주기 or 객체.set_title("타이틀")

# 박스플롯 - hue 변수 추가 
sns.boxplot(x='alive', y='age', hue='sex', data=titan_df, ax=ax2).set(title='BOXPLOT + HUE')

# 바이올린 플롯 - 기본값
sns.violinplot(x='alive', y='age', data=titan_df, ax=ax3).set(title='VIOLINPLOT')

# 바이올린 플롯 - hue 변수 추가 
sns.violinplot(x='alive', y='age', hue='sex', data=titan_df, ax=ax4).set(title='VIOLINPLOT+HUE')

 

 

막대 그래프

# 그래프 객체 생성
fig = plt.figure(figsize=(15,5))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)

# x축, y축에 변수 할당
sns.barplot(x='sex', y='survived', data=titan_df, ax=ax1)

# x축, y축에 변수 할당 후, hue 옵션 추가
sns.barplot(x='sex', y='survived', hue='class', data=titan_df, ax=ax2)

# x축, y축에 변수 할당 후, hue 옵션 추가 후 누적 출력
sns.barplot(x='sex', y='survived', hue='class', dodge=False, data=titan_df, ax=ax3)

# 차트 제목 표시
ax1.set_title('titan survived - sex')
ax2.set_title('titan survived - sex/class')
ax3.set_title('titan survived - sex/class(stacked)')

plt.show()

 

 

 

범주형 데이터의 산점도

import matplotlib.pyplot as plt
import seaborn as sns

# titan
titan_df = sns.load_dataset('titanic')

# set style theme
sns.set_style('whitegrid')

# 그래프 객체 생성
fig = plt.figure(figsize=(15,5))
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

# 이산형 변수의 분포 - 데이터 분산 고려를 안한다면(중복 표시 O)
sns.stripplot(x='class',
             y='age',
             data=titan_df,
             ax=ax1)

# 이산형 변수의 분포 - 데이터 분산 고려를 한다면(중복 표시 X)
sns.swarmplot(x='class',
             y='age',
             data=titan_df,
             ax=ax2)

# 차트 제목 표시
# ax1.set_title('Strip Plot')
# ax2.set_title('Swarm Plot')

plt.show()

'AI > [Visualization]' 카테고리의 다른 글

[Matplotlib] Pie그래프  (0) 2023.02.13
[Matplotlib] 막대바  (0) 2023.02.13
[Matplotlib] 산점도 찍기  (0) 2023.02.13
[Matplotlib] 시각화 첫 단계  (0) 2023.02.07
# 한국어 폰트 적용

import matplotlib
# matplotlib.rcParams['font.family'] = 'Malgun Gothic' # 윈도우즈의 '맑은 고딕'설정
matplotlib.rcParams['font.family'] = 'AppleGothic'    # 맥북 '애플 고딕'설정

matplotlib.rcParams['axes.unicode_minus'] = False

 

# 도형 1
fruit = ['사과','바나나','딸기','오렌지','포도']
result = [7,6,3,2,2]
import matplotlib.pyplot as plt
plt.pie(result)
plt.show()

# 도형 2
# 생성한 원이 타원 -> 원형으로 변환
plt.figure(figsize=(5,5))
plt.pie(result, labels = fruit, autopct = '%.1f%%')
plt.show()

도형 1
도형 2

 

 

# 시계방향순 데이터 정렬

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

# startangle=90 x축 기준 90도 에서 시작 (생략시 0도)
# autopct 소수점 보여줄꺼
# counterclock=False  시계방향

plt.show()

 

explode_value = (0.1, 0,0,0,0)   # 1번째 요소 0.1 만큼 파이에서 나오게

# 시계방향 순으로 데이터 pie_chart를 생성
plt.figure(figsize=(5,5))
plt.pie(result, labels = fruit, autopct = '%.1f%%', startangle =90, counterclock=False, explode=explode_value, shadow=True)

# img 저장하기
plt.savefig('./save_test0.png')
plt.show()


# 사진의 해상도 높이기 dpi(dot per inch)
import matplotlib as mpl
mpl.rcParams['figure.figsize']

# 해상도 보기 dpi를 찍어보기 
mpl.rcParams['figure.dpi']

 

 

 

 

import numpy as np
import matplotlib.pyplot as plt

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

 

<y= x 꼴 그래프 만들어보기>

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

plt.grid()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Saving a figure')

# 위의 이미지 저장 
plt.savefig('./save_test10', dpi=1000)

'AI > [Visualization]' 카테고리의 다른 글

[Seaborn] Seaborn 그래프 형태  (0) 2023.02.13
[Matplotlib] 막대바  (0) 2023.02.13
[Matplotlib] 산점도 찍기  (0) 2023.02.13
[Matplotlib] 시각화 첫 단계  (0) 2023.02.07

 

<2가지 비교사항을 막대바로 정렬해보기>

# 한국어 폰트 적용

import matplotlib
# matplotlib.rcParams['font.family'] = 'Malgun Gothic' # 윈도우즈의 '맑은 고딕'설정
matplotlib.rcParams['font.family'] = 'AppleGothic'    # 맥북 '애플 고딕'설정

matplotlib.rcParams['axes.unicode_minus'] = False

 

<Before, After 설정>

members_id= ['m_01','m_02','m_03','m_04']
before_wo = [27,35,40,33]
after_wo = [30,38,42,37]

 

# plt.bar

# 세로막대기
import matplotlib.pyplot as plt
import numpy as np

n_data = len(members_id) # 4명
index_1 = np.arange(n_data) # Numpy 배열 (0,1,2,3)

plt.bar(index_1, before_wo, tick_label=members_id) # bar(x,y)에서 x=index, y= before_wo
plt.title('Before 세로막대기')
plt.show()

 

 

 

# 가로 막대 그래프를 생성
colors =['r','g','b','m']
plt.barh(index_1,after_wo, color=colors, tick_label = members_id)  # barh <- h만 넣어주면 됨
plt.title('After 세로막대기')
plt.show()

 

<2가지 세로막대기 생성으로 비교해보기>

# 하나의 창에서 두 개의 그래프를 그리자.
barwidth = 0.4
plt.bar(index_1,before_wo, color='c', align='edge', width=barwidth, label='before')
plt.bar(index_1+barwidth,after_wo, color='m', align='edge', width=barwidth, label='after')
plt.legend() # 범례
plt.xlabel('회원 ID')
plt.ylabel('근육량')
plt.title('운동 전후의 근육변화량 비교')
plt.show()

 

'AI > [Visualization]' 카테고리의 다른 글

[Seaborn] Seaborn 그래프 형태  (0) 2023.02.13
[Matplotlib] Pie그래프  (0) 2023.02.13
[Matplotlib] 산점도 찍기  (0) 2023.02.13
[Matplotlib] 시각화 첫 단계  (0) 2023.02.07
# 한국어 폰트 적용

import matplotlib
# matplotlib.rcParams['font.family'] = 'Malgun Gothic' # 윈도우즈의 '맑은 고딕'설정
matplotlib.rcParams['font.family'] = 'AppleGothic'    # 맥북 '애플 고딕'설정

matplotlib.rcParams['axes.unicode_minus'] = False

 

 

 

import matplotlib.pyplot as plt
import numpy as np
height = [165,177,160,180,185,155,172] # 키 데이터
weight = [62,67,55,74,90,43,64] # 몸무게 데이터
plt.scatter(height, weight)

plt.xlabel('Height(cm)')
plt.ylabel('Weight(kg)')
plt.title('Height & Weight')
plt.grid()  # 그리드

plt.scatter(height, weight, s=500, c='r') # s: 마커크기, c: 색

plt.show()

 

 

# 마커 크기를 변경하는 방법

plt.scatter(height, weight, s=500, c='r') # s: 마커 크기, c: 색깔
plt.show()

 

 

 

 

 

# 데이터마다 마커의 크기와 컬러를 다르게 지정

size = 100* np.arange(1, 8)
colors = ['r', 'g', 'b', 'c', 'm', 'k','y'] 
plt.scatter(height, weight, s=size, c=colors)
height = [165,177,160,180,185,155,172] # 키 데이터
weight = [62,67,55,74,90,43,64] # 몸무게 데이터       # 165, 62가 1번째 Red -> 177, 67 Green 순서대로
plt.show()

 

 

 

 

https://hyunmin1906.tistory.com/30

 

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]

# 인구밀도
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, alpha=0.5)
plt.xlabel('경도')
plt.ylabel('위도')
plt.title('지역별 인구밀도')

for x,y, city_name in zip(lon, lat,city):
    plt.text(x,y, city_name) # 경도, 위도에 따른 도시이름 mapping
    
    
plt.show()

'AI > [Visualization]' 카테고리의 다른 글

[Seaborn] Seaborn 그래프 형태  (0) 2023.02.13
[Matplotlib] Pie그래프  (0) 2023.02.13
[Matplotlib] 막대바  (0) 2023.02.13
[Matplotlib] 시각화 첫 단계  (0) 2023.02.07

Matplotlib를 통한 시각화 첫 단계 

# matplotlib
!pip install matplotlib # 라이브러리 설치


import matplotlib.pyplot as plt # 라이브러리 임포트

 

 

값 채워 넣고 라이브러리 실행 (1차식)

data1 = [10,14,19,20,25]
plt.plot(data1)
plt.show()

 


 

2차식 넘파이를 활용하여 만들기

import numpy as np 
x = np.arange(-4.5, 5, 0.5) # 넘파이로 숫자 생성(-4.5 부터 5까지 0.5씩증가)
y = 2*x**2   # y = 2x^2
[x,y]



#[array([-4.5, -4. , -3.5, -3. , -2.5, -2. , -1.5, -1. , -0.5,  0. ,  0.5,
#         1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5]),
# array([40.5, 32. , 24.5, 18. , 12.5,  8. ,  4.5,  2. ,  0.5,  0. ,  0.5,
#         2. ,  4.5,  8. , 12.5, 18. , 24.5, 32. , 40.5])]

시각화하기 

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


 

여러 그래프를 하나의 창에 넣어보기

# 함수 설정하기
import numpy as np
import matplotlib.pyplot as plt

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

 

# 시각화 방법 1
plt.plot(x,y1)
plt.plot(x,y2)
plt.plot(x,y3)
plt.show()

# 더 간단하게도 가능
#plt.plot(x,y1,x,y2,x,y3)
# plt.show()

 


여러 그래프를 여러 창에 넣어보기

# 넘파이로 함수 생성
import numpy as np

# 데이터 생성
x = np.arange(-5,5, 0.1)
y1 = x**2 -2

y2 = 20*np.cos(x)**2

#plt.figure 로 새창을 만들고 (숫자)로 여러 창 생성가능

plt.figure(1) # 1번 그래프를 창에 넣기
plt.plot(x, y1)

plt.figure(2) # 2번 그래프를 창에 넣기
plt.plot(x, y2)

plt.show()

'AI > [Visualization]' 카테고리의 다른 글

[Seaborn] Seaborn 그래프 형태  (0) 2023.02.13
[Matplotlib] Pie그래프  (0) 2023.02.13
[Matplotlib] 막대바  (0) 2023.02.13
[Matplotlib] 산점도 찍기  (0) 2023.02.13

+ Recent posts