import pandas as pd
import json
import requests
import plotly.express as pxplotly 공식예제
DATA
df = px.data.election()
geojson = px.data.election_geojson()두 개의 데이터
두 데이터를 연결하는 매개체
지역구에 대응하는 숫자가 들어있는 칼럼이름(df)
key가 저장된 위치(geojson, df)
df.head()| district | Coderre | Bergeron | Joly | total | winner | result | district_id | |
|---|---|---|---|---|---|---|---|---|
| 0 | 101-Bois-de-Liesse | 2481 | 1829 | 3024 | 7334 | Joly | plurality | 101 |
| 1 | 102-Cap-Saint-Jacques | 2525 | 1163 | 2675 | 6363 | Joly | plurality | 102 |
| 2 | 11-Sault-au-Récollet | 3348 | 2770 | 2532 | 8650 | Coderre | plurality | 11 |
| 3 | 111-Mile-End | 1734 | 4782 | 2514 | 9030 | Bergeron | majority | 111 |
| 4 | 112-DeLorimier | 1770 | 5933 | 3044 | 10747 | Bergeron | majority | 112 |
geojson.keys()dict_keys(['type', 'features'])
geojson['features'][0].keys()dict_keys(['type', 'geometry', 'properties', 'id'])
geojson['features'][0]['properties']{'district': '11-Sault-au-Récollet'}
시각화 예시1
px.choropleth_mapbox(
data_frame= df,
geojson=geojson,
color="Bergeron",
locations="district",
featureidkey="properties.district",
center={"lat": 45.5517, "lon": -73.7073},
mapbox_style="carto-positron",
zoom=9
)fig=px.choropleth_mapbox(
data_frame= df,
geojson=geojson,
color="Bergeron",
locations="district",
featureidkey="properties.district",
center={"lat": 45.5517, "lon": -73.7073},
mapbox_style="carto-positron",
zoom=9
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) # 마진 없애주기시각화 예시2
fig = px.choropleth_mapbox(data_frame= df,
geojson=geojson,
color="Bergeron",
locations="district_id",
featureidkey="id",
center={"lat": 45.5517, "lon": -73.7073},
mapbox_style="carto-positron",
zoom=9)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})한국의 인구수 예제
df=pd.read_csv('https://raw.githubusercontent.com/guebin/2021DV/master/_notebooks/2021-11-22-prov.csv')
df| 행정구역(시군구)별 | 총인구수 (명) | |
|---|---|---|
| 0 | 서울특별시 | 9532428 |
| 1 | 부산광역시 | 3356311 |
| 2 | 대구광역시 | 2390721 |
| 3 | 인천광역시 | 2945009 |
| 4 | 광주광역시 | 1442454 |
| 5 | 대전광역시 | 1454228 |
| 6 | 울산광역시 | 1122566 |
| 7 | 세종특별자치시 | 368276 |
| 8 | 경기도 | 13549577 |
| 9 | 강원도 | 1537717 |
| 10 | 충청북도 | 1596948 |
| 11 | 충청남도 | 2118977 |
| 12 | 전라북도 | 1789770 |
| 13 | 전라남도 | 1834653 |
| 14 | 경상북도 | 2627925 |
| 15 | 경상남도 | 3318161 |
| 16 | 제주특별자치도 | 676569 |
global_distriction_jsonurl='https://raw.githubusercontent.com/southkorea/southkorea-maps/master/kostat/2018/json/skorea-provinces-2018-geo.json'global_dict = json.loads(requests.get(global_distriction_jsonurl).text)global_dict['features'][0].keys()global_dict['features'][0]['properties']fig = px.choropleth_mapbox(data_frame= df,
geojson=global_dict,
color="총인구수 (명)",
locations="행정구역(시군구)별",
featureidkey="properties.name",
center={"lat": 35, "lon": 127},
mapbox_style="carto-positron",
zoom=5)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})