본문 바로가기
카테고리 없음

Python_matplotlib (tool : Google colab) part.1

by Hunihu 2023. 1. 3.

파이썬에서 그래프를 그려보자.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

numpy = 행렬 처리를 위한 패키지

pandas = 데이터 테이블 처리를 위한 패키지

matplotlib.pyplot = 그래프 처리를 위한 패키지

seaborn = Matplotlib을 기반으로 다양한 색상 테마와 통계용 차트 등의 기능을 추가한 시각화 패키지

 

데이터 셋

 

tips = sns.load_dataset('tips')

패키지에서 데이터 테이블을 불러온다.

tips.head()

테이블에서 5개행의 데이터만 축출해보자.

tips.info()

tips 테이블의 컬럼이나 여러 테이블 구성요소를 확인하자.

 

matplotlib.pyplot 모듈을 사용한 시각화

  1. figure 객체 생성.
  2. figure 객체에 subplot(axis)을 생성해서 추가.
  3. subplot에 그래프 그림.
  4. 그래프의 여러가지 옵션들을 설정.
  5. 그래프 보여주기.
# 1. figure 객체 생성
fig = plt.figure()

# 2. 생성된 figure 객체에 suplot을 추가
axis = fig.add_subplot(1, 1, 1) # add_subplot()에서 인덱스는 1부터 시작!

# 3. subplot에 그래프 종류를 선택해서 그림.
axis.hist(x=tips['total_bill'])

# 4. 그래프의 옵션 설정
axis.grid()
axis.set_xlabel('Total Bill')
axis.set_ylabel('Count')
axis.set_title('Histogram')

# 5. 그래프 보여주기
plt.show()

2개의 subplot을 상하로 배치하고 그래프를 그리기.

# 1. figure 생성
fig = plt.figure(figsize=(6, 8))

# 2. subplot 추가
ax1 = fig.add_subplot(2, 1, 1) # add_subplot(211)
ax2 = fig.add_subplot(212) # add_subplot(2, 1, 2)와 동일.

# 3. 각 subplot에 그래프 그림.
ax1.hist(x=tips.total_bill) # 히스토그램
ax2.scatter(x=tips.total_bill, y=tips.tip) # 산점도

# 4. 옵션 설정.
ax1.set_title('Histogram')
ax2.set_title('Scatter plot')
ax2.set_xlabel('Total Bill')
ax2.set_ylabel('Tip')

# 5. 보여주기
plt.show()

 

2개의 subplot을 좌우로 배치하고 그래프를 그리기.

 

# 1. figure 생성
fig = plt.figure(figsize=(12, 3)) # figsize=(width, height)

# 2. subplot 추가
ax1 = fig.add_subplot(121) # add_subplot(1, 2, 1)와 동일. (행,열,인덱스)
ax2 = fig.add_subplot(122) # add_subplot(1, 2, 2)와 동일.


ax1.set_title('Histogram')
ax1.grid()
ax1.set_xlabel('Total bill')
ax1.set_title('Histogram')

ax2.scatter(x=tips.total_bill, y=tips.tip)
ax2.grid()
ax2.set_xlabel('Total bill')
ax2.set_ylabel('Tip')
ax2.set_title('Scatter plot')

# 5. 보여주기
plt.show()
 

plt.subplots() 함수

figure 객체 생성(plt.figure()) + subplot 추가(figure.add_subplot())

 

1개의 figure에 1개의 subplot이 있는 경우

# 1. figure 생성. 2. subplot 생성.
fig, ax = plt.subplots() # nrow=1, ncol=1

# 3. 그래프 그리기.
ax.hist(x=tips.total_bill)

# 4. 옵션 설정.
ax.grid()

# 5. 그래프 보여주기.
plt.show()

 

plt.subplots() 함수를 사용해서 히스토그램과 산점도를 상/하로 배치

ax[index] 인 이유

fig, ax = plt.subplots(nrows=2, figsize=(6,8))

ax[0].hist(x=tips.total_bill)
ax[1].scatter(x=tips.total_bill, y=tips.tip)

plt.show()

 

plt.subplots() 함수를 사용해서 히스토그램과 산점도를 좌/우로 배치

fig, ax = plt.subplots(ncols= 2, figsize=(8,6) )
# print(ax) # -> 1차원 ndarray

ax[0].hist(x=tips.total_bill)
ax[1].scatter(x=tips.total_bill, y=tips.tip)

plt.show()