-
전국 프랜차이즈 빵집(파리바게뜨, 뚜레쥬르) 지점 위치 시각화Data Analysis/LifeStyles 2021. 7. 8. 22:45
이번 포스팅에서는 국내 메이저 프랜차이즈 베이커리 SPC그룹의 파리바게뜨와 CJ그룹의 뚜레쥬르의 지점 위치를 지도에 시각화해보도록 하겠다. 오늘은 공공데이터 포털에서 제공하고 있는 소상공인시장진흥공단_상가(상권)정보_20210331 데이터를 사용하도록 하겠다. 당연히 파이썬을 활용해서 분석할 예정이다.
1. 데이터 가져오기 & 전처리
아래 코드를 돌리면 전국에 위치한 파리바게뜨, 뚜레쥬르 정보를 포함한 상세 데이터를 확인할 수 있을 것이다. 다만 해당 데이터는 올해 3월 기준으로 현재 지점 수과는 다를 수 있다. 이 부분 참고해서 보시기 바란다.
import pandas as pd import os city=os.listdir('~소상공인시장진흥공단_상가(상권)정보_20210331')[1:] df=pd.DataFrame() for i in city: temp=pd.read_csv(f'C:/Users/IGAWorks_Wade/Downloads/소상공인시장진흥공단_상가(상권)정보_20210331/{i}') df=df.append(temp) df=df[~df['상호명'].isnull()] bread=df[(df['상호명'].str.contains('뚜레쥬르')) | (df['상호명'].str.contains('파리바게뜨'))] bread['Brand']=bread['상호명'].apply(lambda x: '파리바게뜨' if '파리바게뜨' in x else '뚜레쥬르') bread=bread.rename(columns={'경도':'lng','위도':'lat'}) reg=pd.DataFrame(bread.groupby(['시도명','Brand']).count()['상호명']) reg=reg.reset_index() paris= reg[reg['Brand']=='파리바게뜨'] tour= reg[reg['Brand']=='뚜레쥬르']
2. 시도별 파리바게뜨, 뚜레쥬르 지점 수
다음으로 시도별 파리바게뜨와 뚜레쥬르 지점 수를 계산해서 비교해보도록 하겠다.
reg=pd.DataFrame(bread.groupby(['시도명','Brand']).count()['상호명']) reg=reg.reset_index() paris= reg[reg['Brand']=='파리바게뜨'] tour= reg[reg['Brand']=='뚜레쥬르'] import matplotlib.pyplot as plt import numpy as np plt.rcParams["font.family"] = 'Malgun Gothic' plt.figure(figsize=(12,10)) x = np.arange(len(reg['시도명'].unique())) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots(figsize=(15,12)) rects1 = ax.bar(x - width/2, paris['상호명'], width, label='파리바게뜨') rects2 = ax.bar(x + width/2, tour['상호명'], width, label='뚜레쥬르') ax.set_xticks(x) ax.set_xticklabels(paris['시도명'],rotation=45) # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('지점 수') ax.set_title('시도별 파리바게뜨, 뚜레쥬르 지점 수 비교') ax.legend() ax.bar_label(rects1, padding=3) ax.bar_label(rects2, padding=3) fig.tight_layout() plt.show()
서울, 경기도에 확실히 파리바게뜨와 뚜레쥬르가 가장 많이 위치한 점을 확인할 수 있고, 모두가 알고 있듯이 전반적으로 파리바게뜨가 지점 수로는 압도적으로 많은 상황이다.
3. Mapbox로 파리바게뜨, 뚜레쥬르 지점 지도에 시각화
다음으로 위에서 뽑은 파리바게뜨, 뚜레쥬르 지점 위치를 가지고 지도에 시각화해보도록 하겠다. 지도 시각화 라이브러리는 Mapbox를 사용하도록 하겠다.
import pandas as pd import os from mapboxgl.utils import * from mapboxgl.viz import * # Must be a public token, starting with `pk` token = '' geo_data = df_to_geojson( df=bread, properties=['상호명', '도로명주소','Brand'], lat='lat', lon='lng', precision=3, filename = "franchise_bakery.geojson" ) geo_data_2 = 'franchise_bakery.geojson' with open(geo_data_2) as f: gdata = json.loads(f.read()) center = [128.033400, 36.801156] match_color_stops = [ ['파리바게뜨','rgb(46,204,113)'], ['뚜레쥬르', 'rgb(231,76,60)'], ] viz = CircleViz( color_function_type='match', color_property='Brand', color_stops=match_color_stops, data=gdata, access_token=token, center=center, zoom=6.2, radius=3, stroke_color='black' ) viz.show() viz.create_html('kore bakery.html')
위 코드가 문제 없이 돌아간다면 아래와 같이 전국에 위치한 파리바게뜨, 뚜레쥬르 지점 데이터를 확인할 수 있다. 초록색은 파리바게뜨, 빨간색은 뚜레쥬르다.
3. 전국 파리바게뜨, 뚜레쥬르 히트맵
다음으로는 파리바게뜨, 뚜레쮸르 지점 수를 기준으로 지도에 히트맵을 시각화하도록 하겠다. 히트맵은 Pydeck 라이브러리를 사용해서 그려보겠다.
import pydeck as pdk heat = pdk.Layer( 'HeatmapLayer', bread, get_position='[lng, lat]', auto_highlight=True, opacity=0.5 ) center = [128.033400, 36.801156] center = [126.986, 37.565] view_state = pdk.ViewState( longitude=center[0], latitude=center[1], zoom=10) r = pdk.Deck(layers=[heat], initial_view_state=view_state) r.show() r.to_html('bakery heatmap.html')
딱히 큰 의미는 없지만 그냥 공부차원에서 히트맵을 그려봤다. 역시 히트맵은 언제 그려도 간지가 난다.
오늘은 딱히 분석이라고 보기 보다는 그냥 파이썬으로 이런 식의 시각화도 가능하구나 정도로 봐주시면 될 것 같다. 나도 해당 포스팅을 참고용으로 코드를 보면서 앞으로 시각화에 많이 활용할 예정이다. 피스
'Data Analysis > LifeStyles' 카테고리의 다른 글
Youtube API에서 3대 운동 검색 결과 가져오기 #1 - 벤치프레스, 데드리프트, 스쿼트 (0) 2021.08.14 서울 열린데이터광장을 통해 버스 정류장 합정역의 승하차 승객 수를 분석해보자~ (0) 2021.08.08 2021 NBA 파이널 - 야니스 아데토쿤보 없는 밀워키 벅스의 희망 크리스 미들턴(Kris Middleton) (0) 2021.07.06 카카오 지도에서 오레노라멘 맛집 리뷰 파이썬으로 크롤링 & 분석 해보자 (0) 2021.07.02 네이버 쇼핑인사이트 - 종근당 락토핏 유산균 검색 클릭량 추이 가져오기 With Python (0) 2021.06.25