Matplotlib¶
대표적인 시각화 library (module)
- Line plot
- area plot
- box plot
- histogram
- scatter
- bar chart, pie chart ... 등 다양한 종류의 차트를 그릴 수 있다.
주로 subpakage인 pyplot 이용한다
import matplotlib.pyplot as plt
Line plot¶
연속적인 값의 경향을 파악할 때 사용한다
ex. 시계열
x축의 자료 위치(x축 눈금) => tick이라고 하며 따로 지정하지 않으면(default) 0, 1, 2, 3...이 된다
# 차트의 제목 설정
plt.title('Line Plot')
# plot()이라는 메소드를 이용해서 line plot 그림
plt.plot([1, 5, 12, 25]) # y축 값을 리스트 형태로 저장
# rendering
plt.show()
그래프 렌더링 : show() 함수
show()는 그래프를 화면에 렌더링하고 마우스 이벤트를 기다린다.
일반 IDE를 사용하면 show를 사용해야 그래프가 그려지지만
jupyter notebook은 shell 단위로 rendering하기 때문에
show를 사용하지 않아도 그래프가 렌더링 된다.
plt.title('Line Plot')
plt.plot([10, 20, 30, 40], [1, 5, 12, 25]) # plt.plot([x축 tick],[y 값])
plt.show()
import numpy as np
import pandas as pd
# excel파일 파이썬으로 불러오기 : openpyxl 설치
df = pd.read_excel('./data/lineplot_sample_data.xlsx') # 1970년부터 2022년까지의 지역별 인구 이동 수
excel 파일을 파이썬으로 불러오기 위해서는 openpyxl이 필요하다
conda install openpyxl
데이터 전처리
df = df.fillna(method='ffill')
전출지가 서울특별시인 데이터만 가져오기
seoul_df = df[(df['전출지별']=='서울특별시') & (df['전입지별'] != '서울특별시')]
seoul_df.drop('전출지별', axis=1, inplace=True)
# 컬럼명 변경
seoul_df.rename({'전입지별' : '전입지'}, axis=1, inplace=True)
C:\Users\Administrator\AppData\Local\Temp\ipykernel_3428\3931576081.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy seoul_df.drop('전출지별', axis=1, inplace=True) C:\Users\Administrator\AppData\Local\Temp\ipykernel_3428\3931576081.py:5: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy seoul_df.rename({'전입지별' : '전입지'}, axis=1, inplace=True)
데이터 원본이 손상된다는 경고가 뜨는데, 경고가 뜨지 않게하려면
import warnings
warnings.filterwarnings(action='ignore')
이 코드를 추가해주면 경고를 무시하게 된다.
import warnings
warnings.filterwarnings(action='ignore')
# 전입지 columns을 행 index로 설정
seoul_df.set_index('전입지', inplace=True)
서울특별시에서 경기도로 이동한 인구의 데이터만 가져오기
s = seoul_df.loc['경기도']
1. 그래프 그리기¶
plt.figure(figsize=(30,6))
plt.title('Seoult to Gyeonggi')
plt.plot(s.index, s.values)
plt.show()
series 데이터에서 index를 x ticks으로 values를 값으로 사용했다.
Histogram¶
변수가 하나인 단변수 데이터의 빈도수를 그래프로 표현한 것이다.
x축을 같은 크기의 여러구간(bin)으로 나누고 y축은 해당 구간안에 포함된 데이터의 개수(빈도, mode)를 표현한다.
x축의 구간(bin)에 따라 히스토그램의 모양이 달라진다.
mpg_df = pd.read_csv('./data/auto-mpg.csv',
header=None) # 컬럼명이 없다는 의미.
mpg_df.columns = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin', 'car name']
mpg_df['mpg'].describe()
count 398.000000 mean 23.514573 std 7.815984 min 9.000000 25% 17.500000 50% 23.000000 75% 29.000000 max 46.600000 Name: mpg, dtype: float64
# matplotlib이 아닌 pandas의 기능을 이용해서 mpg의 histogram 그리기
mpg_df['mpg'].plot(kind='hist',
bins=20, # 최소값과 최대값 사이를 10개의 구간으로 분할
color='blue',
figsize=(10,5))
plt.show()
Scatter (산점도)¶
서로 다른 두 변수 사이의 관계를 나타내는 그래프
2개의 변수의 값을 각각 x축과 y에 하나씩 놓고 데이터 값이 위치하는 (x,y)좌표를 찾아서 그래프에 표현한다.
# mpg(연비)와 weight의 관계
mpg_df.plot(kind='scatter',
x='weight',
y='mpg',
color='red',
s=10,
figsize=(10,6))
plt.show()
Bar plot¶
단변수의 데이터 분포를 알아보기위해서 사용
4분위값을 이용하여 그리는 그래프
- 4분위값을 이용해서 데이터의 분포를 확인할 수 있다.
- outlier를 그래프에 표현해준다.
- 중위값도 선으로 나타내준다.
# 제조국별 연비분포
plt.boxplot(x=[mpg_df.loc[mpg_df['origin']==1,'mpg'],
mpg_df.loc[mpg_df['origin']==2,'mpg'],
mpg_df.loc[mpg_df['origin']==3,'mpg']])
plt.show()
subplot¶
그래프를 여러개 그리는 방법
- Figure : canvas 객체. 그래프를 그리는 도화지 jupyter notebook은 plot()을 사용하면 자동으로 figure 객체를 만들어주지만 canvas의 크기를 임의로 설정하려면 figure객체를 만들어야 한다. figure 객체는 1개 이상의 Axes로 구성된다.
- Axes
- Axis
##### 스타일 #####
plt.style.use('ggplot')
######## subplot ########
fig = plt.figure(figsize=(25,6))
ax1 = fig.add_subplot(1, 2, 1) # add_subplot(행, 열, 몇번째 axes)
ax2 = fig.add_subplot(1, 2, 2)
######## ax 1 ##########
ax1.set_xlabel('year')
ax1.set_ylabel('population')
ax1.plot(s.index, s.values,
marker='o')
####### ax 2 #########
ax2.plot(s.index, s.values,
marker='s',
color='g')
plt.show()
'Programming > Data Visualize' 카테고리의 다른 글
[matplotlib] 그래프에 한글 폰트 깨짐 현상 해결하기 (0) | 2022.03.22 |
---|