matploblib 기초¶
In [1]:
import matplotlib.pyplot as plt #매트랩의 시각화 기능들을 담아놓은게 pyplot이다.
# 한글 폰트 인식
from matplotlib import rc
rc("font", family="Malgun Gothic")
# 아래 두 코드 중 하나 실행하면 됨 (둘이 같은 기능)
# 그린 그래프를 쥬피터 노트북에 바로 나타나게 해주는 설정
%matplotlib inline
#get_ipython().run_line_magic("matplotlib","inline")
matplotlib 그래프 기본 형태
plt.figure(figsize=(10,6))
plt.plot(x,y)
plt.show()
In [18]:
# 가로축 크기가 10, 세로축 크기가 6
plt.figure(figsize=(10,6))
# 그래프 안에 (x축 데이터, y축 데이터) 를 넣어준다.
plt.plot([0,1,2,3,4,5,6,7,8,9],[1,2,3,3,1,-3,-1,5,2,-1])
# 바꾼 내용들을 저장한 후 그걸 그래프로 보여줘라
plt.show()
예제1 : 그래프 기초¶
삼각함수 그리기¶
- np.arrange(a,b,s) : a 부터 b 까지 s 간격으로 데이터 만들어주는 메소드
- np.sin(value)
In [24]:
import numpy as np
t = np.arange(0,12,0.01)
plt.figure(figsize=(10,6))
plt.plot(t,np.sin(t))
plt.plot(t,np.cos(t))
plt.show()
-
- 격자무늬 추가
-
- 그래프 제목 추가
-
- x축, y축 제목 추가
-
- 주황색, 파란색 선 데이터의 구분
In [35]:
def draw_graph() :
plt.figure(figsize = (10,6))
plt.plot(t,np.sin(t), label="sin")
plt.plot(t,np.cos(t), label="cos")
plt.grid(True) # 뒤에 격자
plt.legend(loc="lower left") # 범례 ( 다양한 loc 옵션이 존재함 )
plt.title("Example of signwave") # 타이틀
plt.xlabel("time") # x축
plt.ylabel("Amplitude") # y축
plt.show()
In [36]:
draw_graph()
예제2 : 그래프 커스텀¶
In [37]:
t = np.arange(0,5,0.5)
t
Out[37]:
array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
In [41]:
plt.figure(figsize=(10,6))
plt.plot(t,t,'r--',label='t')
plt.plot(t,t**2,'bs',label='t^2')
plt.plot(t,t**3,'g^',label='t^3')
plt.legend()
plt.grid(True)
plt.title('ex2 : customize the graph')
plt.show()
In [44]:
t = np.arange(0,7,1)
y = [1,3,5,7,4,5,9]
In [48]:
def draw_graph():
plt.figure(figsize=(10,6))
plt.plot(
t,
y,
color='green',
linestyle='dashed', # - 이면 실선, -- 이면 dashed
marker='o', # 마커 모양
markerfacecolor='blue',
markersize=15
)
plt.xlim([-0.5,10]) # x축 데이터 범위
plt.ylim([0.5,9.5]) # y축 데이터 범위
plt.grid()
plt.show()
draw_graph()
예제 3 : scatter plot¶
In [52]:
t = np.array(range(0,10))
y = np.array([9,8,7,9,8,3,2,4,3,4])
In [61]:
def draw_graph():
plt.figure(figsize=(10,6))
plt.scatter(t,y,color='green',marker='^',label='dots')
plt.title('ex3. scatterplot')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.grid()
plt.legend()
plt.show()
draw_graph()
In [63]:
colormap = t
def draw_graph():
plt.figure(figsize=(10,6))
plt.scatter(t,y,s=150,c=colormap,marker='>') # s는 사이즈를 의미
plt.colorbar()
plt.show()
draw_graph()
예제 4 : pandas에서 plot 그리기¶
- matploblib 을 가져와서 사용합니다.
In [2]:
import pandas as pd
import numpy as np
CCTV_Seoul = pd.read_csv('../data/01. Seoul_CCTV.csv', encoding = 'utf-8')
CCTV_Seoul.rename(
columns = {
CCTV_Seoul.columns[0]:'구별',
CCTV_Seoul.columns[1]:'CCTV 수'
},
inplace = True
)
CCTV_Seoul['최근 증가율'] = (
(CCTV_Seoul['2014년']+CCTV_Seoul['2015년']+CCTV_Seoul['2016년'])/CCTV_Seoul['2013년도 이전'] *100
)
pop_Seoul = pd.read_excel('../data/01. Seoul_Population.xls',header=2,usecols="B,D,G,J,N")
pop_Seoul.drop([0],axis=0, inplace=True)
pop_Seoul.rename(
columns = {
pop_Seoul.columns[0]:"구별",
pop_Seoul.columns[1]:"인구수",
pop_Seoul.columns[2]:"한국인",
pop_Seoul.columns[3]:"외국인",
pop_Seoul.columns[4]:"고령자",
},
inplace = True,
)
pop_Seoul['외국인 비율'] = (pop_Seoul['외국인']/pop_Seoul['인구수'] *100)
pop_Seoul['고령자 비율'] = (pop_Seoul['고령자']/pop_Seoul['인구수'] *100)
data_result = pd.merge(CCTV_Seoul,pop_Seoul,how='inner',on='구별')
data_result.drop(['2013년도 이전','2014년','2015년','2016년'],axis=1,inplace=True)
data_result.set_index('구별',inplace=True)
In [3]:
data_result.head(3)
Out[3]:
CCTV 수 | 최근 증가율 | 인구수 | 한국인 | 외국인 | 고령자 | 외국인 비율 | 고령자 비율 | |
---|---|---|---|---|---|---|---|---|
구별 | ||||||||
강남구 | 3238 | 150.619195 | 561052 | 556164 | 4888 | 65060 | 0.871220 | 11.596073 |
강동구 | 1010 | 166.490765 | 440359 | 436223 | 4136 | 56161 | 0.939234 | 12.753458 |
강북구 | 831 | 125.203252 | 328002 | 324479 | 3523 | 56530 | 1.074079 | 17.234651 |
In [5]:
# 세로막대
data_result['인구수'].plot(kind='bar',figsize=(5,5))
Out[5]:
<AxesSubplot:xlabel='구별'>
In [7]:
# 가로막대
data_result['인구수'].plot(kind='barh',figsize=(5,5))
Out[7]:
<AxesSubplot:ylabel='구별'>
'DS_Study > 서울시 CCTV 현황' 카테고리의 다른 글
[DS_study] pandas dataframe으로 plot 그리기 (0) | 2022.05.29 |
---|---|
[DS_study] CCTV, 인구통계 데이터 합치기 (0) | 2022.05.29 |
[DS_study] pandas 데이터 합치기 (0) | 2022.05.29 |
[DS_Study] 데이터 흝어보기 (0) | 2022.05.29 |
[DS_study] pandas dataframe 조건식, 칼럼 추가, 수정, isin(), 제거, 함수 적용 (0) | 2022.05.25 |