티스토리 뷰
제 2장 서울시 범죄 현황 분석¶
구성 및 블로깅 진행과정¶
2-1 데이터 획득하기
2-2 pandas를 이용하여 데이터 정리하기
2-3 지도 정보를 얻을 수 있는 Google Maps
2-4 Google Maps를 이용해서 주소와 위도, 경도 정보 얻기
-------------------------------------------------------
2-5 pandas의 pivot_table 학습하기
2-6 pivot_table을 이용해서 데이터 정리하기
2-7 데이터 표현을 위해 다듬기
-------------------------------------------------------
2-8 좀 더 편리한 시각화 도구 - Seaborn
2-9 범죄 데이터 시각화하기
-------------------------------------------------------
2-10 지도 시각화 도구 - folium
2-11 서울시 범죄율에 대한 지도 시각화
2-12 서울시 경찰서별 검거율과 구별 범죄 발생율을 동시에 시각화하기
출처: 파이썬으로 데이터 주무르기 by 민형기
2-8 좀 더 편리한 시각화 도구 - Seaborn¶
# 몇 개의 사인함수를 그려보자.
# seaborn을 import 할 때는 matplotlib도 같이 import 되어 있어야 한다.
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
x = np.linspace(0, 14, 100)
y1 = np.sin(x)
y2 = 2*np.sin(x+0.5)
y3 = 3*np.sin(x+1.0)
y4 = 4*np.sin(x+1.5)
plt.figure(figsize=(10,6))
plt.plot(x, y1, x, y2, x, y3, x, y4)
plt.show()
# seaborn은 whitegrid라는 스타일을 지원한다.
sns.set_style("whitegrid")
plt.figure(figsize=(10,6))
plt.plot(x, y1, x, y2, x, y3, x, y4)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
# seaborn에 포함되어 있는 데이터셋
# 요일별 점심, 저녁, 흡연 여부 & 식사 금액 & 팁
tips = sns.load_dataset("tips")
tips.head()
# boxplot을 그리는데 x축에는 요일, y축에는 전체 금액을 그린다.
plt.figure(figsize=(8,6))
sns.boxplot(x="day", y="total_bill", data=tips)
plt.show()
#hue라는 옵션을 이용하여 구분할 수 있다.
plt.figure(figsize=(8,6))
sns.boxplot(x='day', y='total_bill', hue='smoker', data=tips, palette='Set3')
plt.show()
위 데이터에서 보면 흡연자가 대체적으로 결제 금액의 범위가 크다는 것을 볼 수 있다.
plt.figure(figsize=(8,6))
sns.swarmplot(x='day', y='total_bill', data=tips, color='.5')
plt.show()
plt.figure(figsize=(8,6))
sns.boxplot(x='day', y='total_bill', data=tips)
sns.swarmplot(x='day', y='total_bill', data=tips, color='.25')
plt.show()
# darkgrid 스타일
# 데이터를 scatter처럼 그리고 직선으로 regression한 그림도 같이 그려주고 유효범위도 ci로 잡아준다.
sns.set_style("darkgrid")
sns.lmplot(x='total_bill', y='tip', data=tips, height=7)
plt.show()
#lmplot도 hue 옵션을 가질 수 있으며 palette로 색상을 지정할 수 있다.
sns.lmplot(x='total_bill', y='tip', hue='smoker', data=tips, palette='Set1', height=7)
plt.show()
uniform_data = np.random.rand(10,12)
uniform_data
sns.heatmap(uniform_data)
plt.show()
sns.heatmap(uniform_data,vmin=0, vmax=1)
plt.show()
# 연도 및 월별 항공기 승객수를 기록한 데이터
# pivot 기능으로 간편하게 월별, 연도별로 구분할 수 있다.
flights = sns.load_dataset('flights')
flights.head()
flights = flights.pivot('month', 'year', 'passengers')
flights.head()
plt.figure(figsize=(10,8))
sns.heatmap(flights)
plt.show()
# heatmap을 사용하면 이런 종류의 데이터는 경향성을 설명하기 참 좋다.
plt.figure(figsize=(10,8))
sns.heatmap(flights, annot=True, fmt='d')
plt.show()
# iris 데이터 불러오기
sns.set(style = 'ticks')
iris = sns.load_dataset('iris')
iris.head(10)
sns.pairplot(iris)
plt.show()
sns.pairplot(iris, hue='species')
plt.show()
sns.pairplot(iris, vars=['sepal_width', 'sepal_length'])
plt.show()
sns.pairplot(iris,x_vars=['sepal_width', 'sepal_length'],
y_vars=['petal_width', 'petal_length'])
plt.show()
anscombe = sns.load_dataset('anscombe')
anscombe.head(5)
sns.set_style('darkgrid')
sns.lmplot(x='x', y='y', data=anscombe.query('dataset=="I"'), ci=None, height=7)
plt.show()
sns.lmplot(x='x', y='y', data=anscombe.query('dataset=="I"'),
ci=None, scatter_kws={'s':80}, height=7)
plt.show()
sns.lmplot(x='x',y='y', data=anscombe.query('dataset == "II"'),
order=1, ci=None, scatter_kws={'s':80}, height=7)
plt.show()
sns.lmplot(x='x', y='y', data=anscombe.query('dataset == "II"'),
order=2, ci=None, scatter_kws={"s":80}, height=7)
plt.show()
sns.lmplot(x='x',y='y', data=anscombe.query('dataset == "III"'),
ci=None, scatter_kws={'s':80}, height=7)
plt.show()
sns.lmplot(x='x', y='y', data=anscombe.query('dataset == "III"'),
robust=True, ci=None, scatter_kws={"s":80}, height=7)
2-9 범죄 데이터 시각화하기¶
# 방금 배운 seaborn을 활용하여 뭔가 성과를 얻어내보자.
# 일단 한글 폰트 문제부터!
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import platform
path = 'c:/Windows/Fonts/malgun.ttf'
from matplotlib import font_manager, rc
if platform.system() == 'Darwin':
rc('font', family='AppleGothic')
elif platform.system() == 'Windows':
font_name = font_manager.FontProperties(fname=path).get_name()
rc('font', family=font_name)
else:
print('Unkonwn system... sorry~~~~')
# 데이터를 다시 한번 확인하고
crime_anal_norm.head()
# 강도와 폭력, 살인과 폭력, 강도와 살인의 상관관계를 확인하자
sns.pairplot(crime_anal_norm, vars=['강도', '살인', '폭력'], kind='reg', height=3)
plt.show()
# 인구수, CCTV개수와 살인, 강도의 상관관계
sns.pairplot(crime_anal_norm, x_vars=['인구수', 'CCTV'],
y_vars=['살인', '강도'], kind='reg', height=3)
plt.show()
cctv와 살인의 상관관계가 낮지만, 자세히 보면 CCTV의 개수가 적을 때 살인이 일어나는 구간이 있다. 즉, CCTV를 기준으로 좌측면에 살인과 강도의 높은 수를 갖는 데이터가 보인다는 것이다.
# 인구수, CCTV와 살인검거율, 폭력검거율의 상관관계
sns.pairplot(crime_anal_norm,
x_vars=['인구수', 'CCTV'],
y_vars=['살인검거율', '폭력검거율'], kind='reg', height=3)
plt.show()
살인 및 폭력 검거율과 CCTV의 관계가 양의 상관관계가 아니다. 오히려 음의 상관계수도 보인다. 또 인구수와 폭력 검거율도 음의 상관관계가 관찰된다.
# 검거율의 합계인 검거 항목 최고 값을 100으로 한정하고 그 값으로 정렬
tmp_max = crime_anal_norm['검거'].max()
crime_anal_norm['검거'] = crime_anal_norm['검거'] / tmp_max * 100
crime_anal_nrom_sort = crime_anal_norm.sort_values(by='검거', ascending=False)
crime_anal_nrom_sort.head()
# 범죄 검거 비율 heatmap으로 시각화
target_col = ['강간검거율', '강도검거율', '살인검거율', '절도검거율', '폭력검거율']
crime_anal_norm_sort = crime_anal_norm.sort_values(by='검거', ascending=False)
plt.figure(figsize = (10,10))
sns.heatmap(crime_anal_norm_sort[target_col], annot=True, fmt='f',
linewidths=.5, cmap='RdPu')
plt.title('범죄 검거 비율 (정규화된 검거의 합으로 정렬)')
plt.show()
결과를 보면 절도 검거율이 다른 검거율에 비해 낮다는 것을 알 수 있다.
그리고 그래프 하단으로 갈수록 검거율이 낮은데 그 속에 강남 3구 중에서 '서초구'가 보인다.
전반적으로 검거율이 우수한 구는 '도봉구','광진구','성동구'로 보인다.
# 범죄 발생 건수 heatmap 시각화
target_col=['강간','강도','살인','절도','폭력','범죄']
crime_anal_norm['범죄'] = crime_anal_norm['범죄'] / 5
crime_anal_norm_sort = crime_anal_norm.sort_values(by='범죄', ascending=False)
plt.figure(figsize=(10,10))
sns.heatmap(crime_anal_norm_sort[target_col], annot=True, fmt='f', linewidth=.5)
plt.title('범죄비율 (정규화된 발생 건수로 정렬)')
plt.show()
발생 건수로 보니 '강남구', '양천구', '영등포구'가 범죄 발생 건수가 높다. 그리고 '송파구'와 '서초구'도 낮다고 볼 수 없다. 그렇다면 정말 강남 3구가 안전하다고 할 수 있을지 의문이 생긴다.
# 내마음에 저장~@
crime_anal_norm.to_csv('pydata/02. crime_in_Seoul_final.csv', sep=',',
encoding='utf-8')
'beginner > 파이썬 분석' 카테고리의 다른 글
시카고 샌드위치 맛집 분석 -1 (0) | 2019.07.05 |
---|---|
서울시 범죄 현황 분석 -4 (2) | 2019.07.03 |
서울시 범죄 현황 분석 -2 (0) | 2019.07.03 |
서울시 범죄 현황 분석 -1 (0) | 2019.07.03 |
서울시 구별 CCTV 현황 분석 -3 (0) | 2019.06.29 |