본문 바로가기
혼공학습단9기

혼자 공부하는 데이터 분석 with 파이썬: 5주차(Chapter 05-1)

by 이두스 2023. 2. 19.

Chapter 05 "데이터 시각화하기

 

Chapter 05-1의 주제는 '맷플롯립 기본 요소 알아보기' 이다.

전체적으로 배울 내용은 다음과 같다

  • 피겨
  • rcParams
  • subplot

05-1 맷플롯립 기본 요소 알아보기

필요한 파일 다운로드

import gdown
import pandas as pd

# ns_book7 다운
gdown.download('https://bit.ly/3pK7iuu','ns_book7.csv', quiet = False)

# pandas dataframe 
ns_book7 = pd.read_csv('ns_book7.csv', low_memory = False)
ns_book7.head()

Figure 객체

  • 모든 그래프 구성 요소를 담고 있는 최상위 객체
  • scatter()로 산점도를 그릴 때 자동으로 피겨 객체가 생성
  • figure()함수로 명시적으로 피겨 객체를 만들면 다양한 그래프 옵션 조절 가능

산점도

# 산점도
import matplotlib.pyplot as plt

plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
plt.show()

그래프 크기 바꾸기: figsize 매개변수

  • figure() 함수를 사용하여 패겨 객체를 만들면 그래프 옵션 조절을 할 수 있음
  • figsize 매개변수에 그래프의 크기를 튜플로 지정할 수 있다.
# figure(): figsize
plt.figure(figsize= (9, 6)) # 너비 9, 높이 6인 피겨 객체
plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
plt.show()

커졌다 !

그래프 실제 크기 확인하기

  • 실제로 9인치가 됐을까? 확인하면 9인치는 나오지 않는다.
  • DPI(dot per inch, 1인치를 몇 개의 점으로 표현하는지) 설정 확인이 필요
  • 컴퓨터 화면의 해상도를 말할 때 사용. 2560 x 1600 픽셀의 해상도와 227DPI를 가지면 실제 화면크기는 2560/227=11.3인치와 1600/227=7인치를 가지게 됨
  • 맷플롯립의 기본 DPI는 72
# 900 x 600 픽셀크기의 그래프 그리기
plt.figure(figsize=(900/72, 600/72))
plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
plt.show()

실제 900 x 600보다는 작음. 코랩은 그래프 주변에 공백을 최소화하는 타이트 레이아웃을 사용하기 때문.
# 타이트 레이아웃 사용하지 않기: bbox_inches 옵션
%config InlineBackend.print_figure_kwargs = {'bbox_inches': None}
plt.figure(figsize=(900/72, 600/72))
plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
plt.show()

# 다시 타이트한 레이아웃으로 가기
%config InlineBackend.print_figure_kwargs = {'bbox_inches': 'tight'}

 

그래프 크기 바꾸기: dpi 매개변수

# dpi 매개변수
plt.figure(dpi = 144)
plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
plt.show()

마커까지 거대해졌

 

 

rcParams 객체

DPI 기본값 바꾸기

plt.rcParams['figure.dpi'] = 100

산점도 마커 모양 바꾸기

# 기본값
plt.rcParams['scatter.marker']
# 결과
# 'o'

# 별 모양으로 바꾸기
plt.rcParams['scatter.marker'] = '*'

plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
plt.show()

반짝반짝 별로 바뀌었다

# marker 매개변수로 바꾸기
plt.scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1, marker = '+')
plt.show()

rcParams 객체에서 설정할 수 있는 기본값의 전체 목록
 - rcParams 객체 설정 목록
https://matplotlib.org/stable/api/matplotlib_configuration_api.html#default-values-and-styling
 - 각 항목의 기본값 목록
https://matplotlib.org/stable/tutorials/introductory/customizing.html#the-default-matplotlibrc-file

 

여러 개의 서브플롯 출력하기 : Axes 클래스

서브플롯 그리기: subplots() 함수

  • subplot 함수로 두 개의 서브플롯을 그리고 싶다면 매개변수에 2
  • 배열의 원소에서 각각 그릴 함수 호출.
fig, axs = plt.subplots(2)

# 1
axs[0].scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)

# 2
axs[1].hist(ns_book7['대출건수'], bins = 100)
axs[1].set_yscale('log')

fig.show()

Figure 클래스 객체인 fig에 Axis 클래스 객체인 axs[0], axs[1]을 서브플롯으로 추가한다고 생각하면 된다
# figsize로 크기 조절과 set_title()로 제목 넣기
fig, axs = plt.subplots(2, figsize = (6, 8))

# 1
axs[0].scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
axs[0].set_title('scatter plot')


# 2
axs[1].hist(ns_book7['대출건수'], bins = 100)
axs[1].set_title('histogram')
axs[1].set_yscale('log')

서브플롯을 가로로 나란히 출력하기

  • subplots() 함수에 행과 열을 지정하면 원하는 서브플롯 개수의 피겨를 만들 수 있음.
  • subplots(2)는 2행임.
    • subplots(1,2)로 1행 2열
    • set_title로 제목
    • set_xlabel()set_ylabel()로 각 축의 이름도 설정
# figsize로 크기 조절과 set_title()로 제목 넣기
# subplots(1,2)로 1행 2열
# set_xlabel()과 set_ylabel()로 각 축의 이름도 설정
fig, axs = plt.subplots(1, 2, figsize = (10, 4))

# 1
axs[0].scatter(ns_book7['도서권수'], ns_book7['대출건수'], alpha = 0.1)
axs[0].set_title('scatter plot')
axs[0].set_xlabel('number of books')
axs[0].set_ylabel('borrow count')

# 2
axs[1].hist(ns_book7['대출건수'], bins = 100)
axs[1].set_title('histogram')
axs[1].set_yscale('log')
axs[1].set_xlabel('borrow count')
axs[1].set_ylabel('frequency')

fig.show()


실습코드

https://colab.research.google.com/drive/1G9PplejTQXMtOzH1cAbSA9bdOFSiNO-m?usp=sharing

 

혼공분석_5주차-1.ipynb

Colaboratory notebook

colab.research.google.com