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

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

by 이두스 2023. 2. 19.

Chapter 05 "데이터 시각화하기

 

Chapter 05-2의 주제는 '선 그래프와 막대 그래프 그리기' 이다.

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

  • 선 그래프
  • 막대 그래프

05-2 선 그래프와 막대 그래프 그리기

필요한 파일 다운로드

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()

연도별 발행 도서 개수 구하기: value_counts() 사용

# 연도별 도서 개수 : value_counts()
count_by_year = ns_book7['발행년도'].value_counts()
count_by_year

# 오름차순 정렬: sort_index()
count_by_year = count_by_year.sort_index()
count_by_year

# 잘못된 데이터(2650년 등등) 2030년 이하의 값만 저장
count_by_year = count_by_year[count_by_year.index <= 2030]
count_by_year

 

주제별 도서 개수 구하기

  • '주제분류번호' 앞의 번호가 주제별로 분류
  • value_counts() 사용
    • NaN이 포함되어있어서 -1로 변환해줌
# value_counts() 사용

import numpy as np

# NaN이 포함되어있어서 -1로 변환해줌
def kdc_1st_char(no):
  if no is np.nan:
    return '-1'
  else: 
    return no[0]

count_by_subject = ns_book7['주제분류번호'].apply(kdc_1st_char).value_counts()
count_by_subject

 

 

선 그래프 그리기

# 설정
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 100

# line plot
plt.plot(count_by_year.index, count_by_year.values)
plt.title('Books by year')
plt.xlabel('year')
plt.ylabel('number of books')
plt.show()

선 모양과 색상 바꾸기

  • linestyle 매개변수
    • 실선: '-'
    • 점선: ':'
    • 쇄선: '-.'
    • 파선: '--'
  • color 매개변수: 16진수나 지정가능
  • marker 매개변수
# line plot: linestyle, color
plt.plot(count_by_year, marker='.', linestyle = ':', color = 'red')
plt.title('Books by year')
plt.xlabel('year')
plt.ylabel('number of books')
plt.show()

# 마커, 선 모양, 색깔 합치기 가능
plt.plot(count_by_year, '.:r')

이렇게 써도 결과는 같다.

 

# 별 모양 마커, 실선, 녹색
plt.plot(count_by_year, '*-g')
plt.title('Books by year')
plt.xlabel('year')
plt.ylabel('number of books')
plt.show()

선 그래프 눈금 개수 조절 및 마커에 텍스트 표시하기

  • x축 눈금: xticks()
    • 10년씩 주기로 하기 위해 range()
    • 연도별 발행 도서 개수를 슬라이스연산을 이용해 5개씩 건너뛰기
    • items() 메서드로 인덱스와 값을 감싼 튜플 얻기
  • 그래프에 값 표시: annotate() 함수
    • 그래프에 나타낼 문자열, x,y좌표를 튜플로 지정
# 눈금, 마커에 텍스트
plt.plot(count_by_year, '*-g')
plt.title('Books by year')
plt.xlabel('year')
plt.ylabel('number of books')

plt.xticks(range(1947, 2030, 10))
for idx, val in count_by_year[::5].items():
  plt.annotate(val, (idx, val))

plt.show()

텍스트가 거슬린다. 어떻게 조금 띄어놓을 수 있을까.

# 텍스트를 마커에서 조금 떼어놓기: xytext 매개변수
plt.plot(count_by_year, '*-g')
plt.title('Books by year')
plt.xlabel('year')
plt.ylabel('number of books')

plt.xticks(range(1947, 2030, 10))
for idx, val in count_by_year[::5].items():
  plt.annotate(val, (idx, val), xytext=(idx+1, val+10))

plt.show()

x 축은 구분이 되지만 y 축은 차이가 없다. y축의 스케일이 더 크기 때문이다.
상대적인 위치를 포인트나 픽셀 단위로 지정해야함: textcoords 매개변수

# textcoords 매개변수
plt.plot(count_by_year, '*-g')
plt.title('Books by year')
plt.xlabel('year')
plt.ylabel('number of books')

plt.xticks(range(1947, 2030, 10))
for idx, val in count_by_year[::5].items():
  plt.annotate(val, (idx, val), xytext=(2, 2), textcoords = 'offset points')

plt.show()

 

 

 

막대 그래프 그리기

  • bar() 함수
# bar plot
plt.bar(count_by_subject.index, count_by_subject.values)
plt.title('Books by year')
plt.xlabel('subject')
plt.ylabel('number of books')
for idx, val in count_by_subject.items():
  plt.annotate(val, (idx, val), xytext=(0, 2), textcoords='offset points')
plt.show()

텍스트 정렬, 막대 조절 및 색상 바꾸기

  • annotate() 함수 속에서 처리
    • 텍스트 위치 조절: ha 매개변수(기본은 'right')
    • 텍스트 크기 조절: fontsize 매개변수
    • 텍스트 색깔: color 매개변수
  • bar()
    • 막대 두께 조절: width 매개변수(기본 0.8)
    • 막대 색깔: color 매개변수
# bar plot
# 막대 두께, 색깔
plt.bar(count_by_subject.index, count_by_subject.values, 
        width=0.7, color='blue')

plt.title('Books by year')
plt.xlabel('subject')
plt.ylabel('number of books')

# 텍스트 위치, 크기, 색깔
for idx, val in count_by_subject.items():
  plt.annotate(val, (idx, val), xytext=(0, 2), textcoords='offset points',
               fontsize = 8, ha = 'center', color = 'green')
plt.show()

 

가로 막대 그래프 그리기

  • barh() 함수
    • 막대 두께: height 매개변수
    • x축과 y축 이름이 바뀜
  • annotate()
    • idx, val가 val, idx로
    • ha가 아닌 va로 텍스트 정렬
# bar plot
# 가로 막대
plt.barh(count_by_subject.index, count_by_subject.values, 
        height=0.7, color='blue')
plt.title('Books by year')
plt.xlabel('number of books')
plt.ylabel('subject')
for idx, val in count_by_subject.items():
  plt.annotate(val, (val, idx), xytext=(2, 0), textcoords='offset points',
               fontsize = 8, va = 'center', color = 'green')
plt.show()


기본미션

선택미션


실습코드

https://colab.research.google.com/drive/1AIlCk2rhp0VqFELLpJU2otalhjLbSMTn?usp=sharing

 

혼공분석_5주차-2.ipynb

Colaboratory notebook

colab.research.google.com