[Python] 데이터 시각화

2021. 4. 29. 17:56Python/문법

chapter2. 데이터시각화_10가지chart_final.ipynb
1.15MB

Ver. Jupyter Notebook (Anaconda3)

 

시각화 하기 위해 필요한 데이터 install

# Anaconda Prompt (Anaconda3)
pip install tqdm
pip install selenium

 

▶ 데이터 시각화

>>> import pandas as pd
>>> import numpy as np

>>> import matplotlib.pyplot as plt   # 시각화 라이브러리
>>> import seaborn as sns                # 시각화 라이브러리

>>> from tqdm import tqdm_notebook   # for문 진행상황을 게이지로 알려줌

# 에러 무시

>>> import warnings
>>> warnings.filterwarnings(action='ignore')

 

▶column 차트

column 그래프 그리기(필수)
>>> plt.figure(figsize=(20, 7))                                                         # 그래프 크기(가로, 세로)
>>> runner_state sns.countplot('State', data=USA_runner)      # 그래프 함수 : sns.countplot() 사용

# column 그래프 부가 설명(옵션)
>>> runner_state.set_title('Number of runner by State - USA', fontsize=30)   # 제목
>>> runner_state.set_xlabel('State', fontdict={'size':16})                                  # x축 이름
>>> runner_state.set_ylabel('Number of runner', fontdict={'size':16})             # y축 이름

>>> 
plt.show()

# column 그래프 그리기(필수)
>>> plt.figure(figsize=(20, 10))
>>> runner_state sns.countplot('State', data=USA_runner, hue='M/F', palette={'F' : 'y', 'M' : 'b'})
# hue: columns명 기준으로 데이터를 구분          # palette: 색상 (y: 노랑, b: 파랑)

# column 그래프 부가 설명(옵션)
>>> runner_state.set_title('Number of runner by State - USA', fontsize=30)   # 제목
>>> runner_state.set_xlabel('State', fontdict={'size':16})                                  # x축 이름
>>> runner_state.set_ylabel('Number of runner', fontdict={'size':16})             # y축 이름

>>> 
plt.show()

 

▶ Dual Axis, 파레토 차트

>>> fig, barChart = plt.subplots(figsize=(20,10))

# bar에 x, y값 넣어서 bar chart 생성 (파랑)
>>> barChart.bar(x, y)

# line chart 생성 (초록, 누적 값)
>>> lineChart = barChart.twinx()  # twinx() : 두 개의 차트가 서로 다른 y 축, 공통 x 축을 사용하게 해줌
>>> lineChart.plot(x, ratio_sum, '-g^', alpha = 0.5)  # alpha:투명도
# -: 선
# ^: 세모, s : sqaured, o : circle
# g : green, b: blue, r: red

오른쪽 축(라인 차트 축) 레이블
>>> ranges = lineChart.get_yticks() # y차트의 단위들
>>> lineChart.set_yticklabels(['{0:.1%}'.format(x) for x in ranges])
# 0.1% : 소수점 첫 째자리 까지 표현
# 0.2% : 소수점 둘 째자리 까지 표현

라인차트 데이터 별 %값 주석(annotation)
>>> ratio_sum_percentages = ['{0:.0%}'.format(x) for x in ratio_sum]
>>> for i, txt in enumerate(ratio_sum_percentages):
           lineChart.annotate(txt, (x[i], ratio_sum[i]), fontsize=12)

x, y label만들기
>>> barChart.set_xlabel('Age', fontdict={'size':16})
>>> barChart.set_ylabel('Number of runner', fontdict={'size':16})

plot에 title 만들기
>>> plt.title('Dual Axis Chart - Number of runner by Age', fontsize=18)

>>> plt.show()

 

▶ Pie chart

>>> plt.subplots(figsize=(7,7))

pie chart 만들기(차트 띄우기, labels 달기, 각 조정, 그림자, 값 소숫점 표시)
>>> plt.pie(marathon_2015_2017['M/F'].value_counts(), explode=(0, 0.1), labels=labels, startangle=90, shadow=True, autopct='%.2f')

# 라벨, 타이틀 달기
>>> plt.title('Male vs Female', fontsize=18)

# 레전드 달기
>>> pltt.legend(['Male', 'Female'], loc='upper right')

>>> plt.show()

 

▶ Line chart

>>> plt.subplots(figsize=(20, 10))

# .: 점선 / -: 실선 / ^: 삼각형 / o: 원 / s: 사각형
>>> plt.plot(xData, yData_full, '.')
>>> plt.plot(xData, yData_30K, '-')
>>> plt.plot(xData, yData_20K, '^')
>>> plt.plot(xData, yData_10K, 'o')

>>> plt.legend(['Full', '30K', '20K', '10K'], loc='upper left')

>>> plt.show()

 

▶ Scatter chart

>>> plt.subplots(figsize=(20, 20))

>>> plt.plot(x_maley_male, '.', color='b', alpha=0.5)
>>> plt.plot(x_femaley_female, '.', color='r', alpha=0.5)

# label과 title 정하기
>>> plt.xlabel('Age', fontsize=30)
>>> plt.ylabel('Official Time(second)', fontsize=30)
>>> plt.title('Distribution by Running time and Age', fontsize=30)

>>> plt.legend(['Male', 'Female'], loc='upper left')

>>>
plt.show()

 

▶ Bubble chart

>>> plt.subplots(figsize=(20, 10))

scatter chart 적용
>>> plt.scatter(marathon_count.Lat, marathon_count.Long, s=marathon_count.Count, alpha=0.5)

# 타이틀, 라벨 달기
>>> plt.title('Runners location at 2nd hours')
>>> plt.xlabel('Latitude')
>>> plt.ylabel('Longitude')

# 위치 별 Count값 넣기
>>> for i, txt in enumerate(marathon_count.Count):
>>>     plt.annotate(txt, (marathon_count.Lat[i], marathon_count.Long[i]), fontsize=20)

>>> plt.show()

 

▶ Heat map

subplots()에선 두개의 값을 받을 수 있는데 figure 와 axes 값을 받을 수 있다.
여기서 변수명은 상관 없지만, 순서가 중요하다.

fig란 figure로써 - 전체 subplot을 말한다.
ex) 서브플로안에 몇개의 그래프가 있던지 상관없이  그걸 담는 하나. 전체 사이즈를 말한다.

ax는 axe로써 - 전체 중 낱낱개를 말한다 ex) 서브플롯 안에 2개(a1,a2)의 그래프가 있다면 a1, a2 를 일컬음.

>>>
 f, ax = plt.subplots(figsize=(10,20))
>>> sns.heatmap(marathon, annot=True, fmt='d', linewidths=.5, ax=ax)  # cmap='Accent'

>>> plt.show()

 

▶ Histogram

>>> plt.subplots(figsize=(7,7))

displot 함수로 분포 그리기
>>> age_count = sns.distplot(marathon_2015_2017.Age)

# 제목, x라벨 ,y라벨 지정
>>> age_count.set_title('Distribution Rate by Ages', fontsize=18)
>>> age_count.set_xlabel('Ages', fontdict={'size':16})
>>> age_count.set_xlabel('Distibution Rate', fontdict={'size':16})

>>> plt.show()

 

▶ Box plot

>>> plt.subplots(figsize=(7,7))

씨본의 스타일 지정
>>> sns.set(style='ticks', palette = 'pastel')
# style = "ticks", "whitegrid" / palette = "pastel", "Set3"

박스플롯 그리기
>>> sns.boxplot(x='M/F', y="Pace", palette=['b', 'r'], data=USA_runner)

 

▶ Geo chart with Folium

>>> import folium
>>> from folium.plugins import HeatMap

Folium marathon map 그리기
>>> marathon_map = folium.Map(location=[42.324830, -71.259660],
>>>                          tiles='OpenStreetMap',  # 지도 타일 형태  # tiles='Stamen Toner', 'Stamen Terrain'
>>>                          zoom_start=11)

>>> HeatMap(marathon_count, radius=25).add_to(marathon_map)

 

'Python > 문법' 카테고리의 다른 글

[python] numpy  (0) 2021.05.03
[python] crawler  (0) 2021.04.30
[python] kaggle, boston marathon  (0) 2021.04.29
[python] 외부데이터  (0) 2021.04.29
[Python] 정리  (0) 2021.04.29