잘잔디 2023. 5. 2. 15:09

folium의 document

https://python-visualization.github.io/folium/quickstart.html

folium 이란

  • 파이썬 라이브러리로 지도 데이터를 시각화하는데 아주 쉽게 도와준다
  • leaflet.js를 기반으로 만들어졌다
  • 지도에 마커를 표현하거나 범위를 나타내는 다양한 도형을 입력할 수 있다.
  • 우리는 folium을 사용하여 지도에다가 뭔가를 그리려 한다
  • conda에 설치되어 있지 않기 때문에 conda install -c conda-forge folium을 입력해줘야 한다.
import folium
import pandas as pd
import numpy as np
import seaborn as sns
import folium
latitude , longitude = (37.468251,126.886212)
m = folium.Map(location=[latitude,longitude],
               zoom_start = 17,
               width = 750,
               height = 500
              )
folium.Marker([latitude,longitude],
             popup = '플레이데이터',
             tooltip = '플레이데이터').add_to(m)

위도, 경도를 알아내는 방법.

  • google map 들어가서 원하는 위치-> 우클릭 -> 주변검색 누르면 위도 경도가 나온다.(왼쪽이 위도, 오른쪽이 경도)
survey_raw_df = pd.read_csv('C:/Chang_git/Data/survey_results_public.csv',index_col = 'ResponseId') 
#국가별 위치가 기록된 json 파일 주소를 countries_geojson에 담는다.
countries_geojson = '<https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json>'
countries_geojson # 국가별 좌표 값을 가진다(국가 그림그리는 점점들이 저장되어 있고 이를 이어서 한나라로 이름을 부여 한것임.)

country_counts = survey_raw_df.Country.value_counts()
country_counts_df = pd.DataFrame({'Country': country_counts.index,'Count': country_counts.values})
country_counts_df

Country Count

0 United States of America 13543
1 India 6639
2 Germany 5395
3 United Kingdom of Great Britain and Northern I… 4190
4 Canada 2490
175 Monaco 1
176 Djibouti 1
177 Seychelles 1
178 Solomon Islands 1
179 Saint Kitts and Nevis 1

180 rows × 2 columns

  • 위 링크의 json 속성 feature.properties.name의 값과 우리가 csv에서 가져온 country name이 일치해야 한다.
  • 이 중 Russian Federation의 값이 불일치해서, 이를 Russia로 변경해 준다.
#country_counts_df.at[12,'Country'] # 'Russian Federation'이 출력됨.
country_counts_df.at[12,'Country'] = 'Russia'
  • Choropleth는 데이터를 담고 있는 Pandas DataFrame/Series와
  • 기하학 데이터를 담는 Geo/TopoJSON을 바인딩하여 쉽게 시각화 표현할 수 있도록 돕는다.
m = folium.Map(location = [30,0],zoom_start=2)

folium.Choropleth(
    geo_data = countries_geojson,
    data = country_counts_df,
    columns = ['Country','Count'],
    key_on = 'feature.properties.name' ,# JSON안에 얘를 기준으로 columns에 담은 값과 mapping하겠다.
    threshold_scale = [1,30,100,300,1_000,3_000,10_000,14_000],#색상에 대한 bins라고 보면된다.
    fill_color = 'YlGn',#color thema
    fill_opacity = 0.7,#채우는 것에 대한 투명도
    line_opacity = 0.2,#라인에 대한 투명도
    legend_name= 'Respondents',#범례명명
).add_to(m)#지도에 이 객체를 추가

folium.LayerControl().add_to(m)
m.save('Country.html') # html 파일로 우리가 그린 그림을 저장한다.
m

#서울시 행정구역에 대한 출력. JSON파일이 있다면 데이터 가공하여 해당 JSON과 맞물리게 표를 만들 수 있다.
seoul_geojson="<https://raw.githubusercontent.com/southkorea/seoul-maps/master/kostat/2013/json/seoul_municipalities_geo_simple.json>"
m = folium.Map(
    location=[37.57, 126.99],
    zoom_start=11,
)
folium.Choropleth(
    geo_data=seoul_geojson,
    fill_color="#22AA44",
    fill_opacity=0.4,
    line_opacity=1,
).add_to(m)
m