본문 바로가기
python

[python 그래프] 데이터 분석 그래프 종류

by _avocado_ 2020. 9. 2.

<주피터 노트북 설정>

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

# 그래프 표현방식 설정
%matplotlib notebook 

# 그래프에 한글 폰트 설정
from matplotlib import font_manager, rc, rcParams
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
rcParams['axes.unicode_minus'] = False

# 그래프 크기 설정
rcParams["figure.figsize"] = (6,4)

 

<사용 데이터>

 

- 야구 데이터

1. df_lineup : 1번부터 9번까지 타순

2. df : 2019년 타자 100명의 데이터

 

<목차>

0. 기본 문법

1. 선 그래프 - line plot

2. 막대그래프 - bar plot

    2-1 가로 막대그래프 -barh plot

3. 개수 그래프 - count plot

4. 산점도 - scatter plot

5. 히스토그램 - histogram

6. 상자 그림 - box plot


  • matplotlib, seaborn, pandas를 이용한 방법을 각각 알아보자

0. 기본 문법

  • matplotlib
plt.plottype(x축, y축(여러개 가능))
plt.plottype(data=df,x='x축이름',y='y축이름')

 

  • seaborn
sns.plottype(x=x축, y=y축)
sns.plottype(data=df,x='x축이름',y='y축이름')

 

  • pandas
data.plot(x='x축이름',y='y축이름', kind='plottype')

1. 선 그래프 - line plot

- 야구 타선의 타율과 장타율

  • matplotlib
plt.figure() # 도화지 생성
x = df_lineup.index # 타순
y = df_lineup['타율'] # 타율
y2 = df_lineup['장타율'] # 장타율
plt.plot(x,y,y2)

  • seaborn
plt.figure() # 도화지 생성
sns.lineplot(data=df_lineup,x=df_lineup.index,y='타율')
sns.lineplot(data=df_lineup,x=df_lineup.index,y='장타율')

  • pandas
df_lineup.plot(y=['타율','장타율'])


2. 막대 그래프 - bar plot

- 타순의 선수별 홈런 개수

  • matplotlib
plt.figure() # 도화지 생성
x = df_lineup['선수명']
y = df_lineup['홈런']
plt.bar(x,y)

  • seaborn
plt.figure()
sns.barplot(data=df_lineup, x='선수명', y='홈런')

  • pandas
df_lineup.plot(x='선수명',y='홈런',kind='bar')

2-1. 가로 막대 그래프 - barh plot

  • matplotlib
plt.figure()
x = df_lineup['선수명']
y = df_lineup['홈런']
plt.barh(x,y)

  • seaborn
# x,y에 따 알아서 바꿔준다.
plt.figure()
sns.barplot(data=df_lineup,x='홈런',y='선수명')

  • pandas
df_lineup.plot(x='선수명',y='홈런',kind='barh')


3. 개수 그래프 - count plot

- 팀별 소속 선수 그래프

  • matplotlib
# 팀별 선수 카운트
# 직접 데이터를 편집하여 x,y를 만들어야한다.
x = df['팀명'].unique()
y = df.groupby('팀명')['선수명'].count()
plt.figure()
plt.bar(x,y)

  • seaborn
# x 값만 설정한다.
plt.figure()
sns.countplot(data=df,x='팀명')

  • pandas(matplotlib과 같다. 생략)

4. 산점도 - scatter plot

- 삼진과 홈런의 관계를 그려보자

  • matplotlib
x = df['삼진']
y = df['홈런']
plt.figure()
plt.scatter(x,y)

 

  • seaborn
plt.figure()
sns.scatterplot(data=df,x='삼진',y='홈런')

  • pandas
df.plot(x='삼진',y='홈런',kind='scatter')


5. 히스토그램 - histogram

- 100명 타자의 타율 히스토그램을 그려보자

  • matplotlib
# 타율 히스토그램
plt.figure()
plt.hist(df['타율'],bins=15) # bins = '나눌 x축 구간의 수'

  • seaborn
plt.figure()
sns.distplot(df['타율'])
# 밀도함수까지 함께 그려준다.

  • pandas
# 특이하게 y에 입력하여야 한다.
df.plot(y='타율',kind='hist')

댓글