1. folium.Map 파라미터
https://python-visualization.github.io/folium/modules.html#module-folium.map
folium — Folium 0.14.0 documentation
folium Make beautiful, interactive maps with Python and Leaflet.js class folium.folium.GlobalSwitches(no_touch=False, disable_3d=False) Bases: branca.element.Element class folium.folium.Map(location=None, width='100%', height='100%', left='0%', top='0%', p
python-visualization.github.io
class folium.folium.Map(location=None, width='100%', height='100%', left='0%', top='0%', position='relative', tiles='OpenStreetMap', attr=None, min_zoom=0, max_zoom=18, zoom_start=10, min_lat=- 90, max_lat=90, min_lon=- 180, max_lon=180, max_bounds=False, crs='EPSG3857', control_scale=False, prefer_canvas=False, no_touch=False, disable_3d=False, png_enabled=False, zoom_control=True, **kwargs)
Parameters
- location (tuple or list, default None) – Latitude and Longitude of Map (Northing, Easting).
- width (pixel int or percentage string (default: '100%')) – Width of the map.
- height (pixel int or percentage string (default: '100%')) – Height of the map.
- tiles (str or TileLayer or xyzservices.TileProvider, default ‘OpenStreetMap’) – Map tileset to use. Can choose from a list of built-in tiles, pass a xyzservices.TileProvider, pass a custom URL, pass a TileLayer object, or pass None to create a map without tiles. For more advanced tile layer options, use the TileLayer class.
- min_zoom (int, default 0) – Minimum allowed zoom level for the tile layer that is created.
- max_zoom (int, default 18) – Maximum allowed zoom level for the tile layer that is created.
- zoom_start (int, default 10) – Initial zoom level for the map.
- attr (string, default None) – Map tile attribution; only required if passing custom tile URL.
- crs (str, default 'EPSG3857') – Defines coordinate reference systems for projecting geographical points into pixel (screen) coordinates and back. You can use Leaflet’s values : * EPSG3857 : The most common CRS for online maps, used by almost all free and commercial tile providers. Uses Spherical Mercator projection. Set in by default in Map’s crs option. * EPSG4326 : A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. * EPSG3395 : Rarely used by some commercial tile providers. Uses Elliptical Mercator projection. * Simple : A simple CRS that maps longitude and latitude into x and y directly. May be used for maps of flat surfaces (e.g. game maps). Note that the y axis should still be inverted (going from bottom to top).
- control_scale (bool, default False) – Whether to add a control scale on the map.
- prefer_canvas (bool, default False) – Forces Leaflet to use the Canvas back-end (if available) for vector layers instead of SVG. This can increase performance considerably in some cases (e.g. many thousands of circle markers on the map).
- no_touch (bool, default False) – Forces Leaflet to not use touch events even if it detects them.
- disable_3d (bool, default False) – Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning (which may cause glitches in some rare environments) even if they’re supported.
- zoom_control (bool, default True) – Display zoom controls on the map.
- **kwargs – Additional keyword arguments are passed to Leaflets Map class: https://leafletjs.com/reference.html#map
ReturnsReturn type
Folium Map Object
Examples
>>> m = folium.Map(location=[45.523, -122.675], width=750, height=500)
>>> m = folium.Map(location=[45.523, -122.675], tiles="cartodb positron")
>>> m = folium.Map(
... location=[45.523, -122.675],
... zoom_start=2,
... tiles="https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=mytoken",
... attr="Mapbox attribution",
... )
그렇다고 한다.
* 실습해보기
zoom_start가 커질수록 가까이 가는듯.
서울시청을 중심으로 지도 보여주기
map = folium.Map(location=[37.5666805, 126.9784147], zoom_start=19, max_zoom=20)
map
도큐먼트에 보면 max_zoom은 디폴트값이 18이기 때문에 19만큼 확장하려면 max_zoom을 그 이상으로 키워줘야함.
2. folium.Choropleth 파라미터
class folium.features.Choropleth(geo_data, data=None, columns=None, key_on=None, bins=6, fill_color=None, nan_fill_color='black', fill_opacity=0.6, nan_fill_opacity=None, line_color='black', line_weight=1, line_opacity=1, name=None, legend_name='', overlay=True, control=True, show=True, topojson=None, smooth_factor=None, highlight=None, use_jenks=False, **kwargs)
Bases: folium.map.FeatureGroup
Apply a GeoJSON overlay to the map.
Plot a GeoJSON overlay on the base map. There is no requirement to bind data (passing just a GeoJSON plots a single-color overlay), but there is a data binding option to map your columnar data to different feature objects with a color scale.
If data is passed as a Pandas DataFrame, the “columns” and “key-on” keywords must be included, the first to indicate which DataFrame columns to use, the second to indicate the layer in the GeoJSON on which to key the data. The ‘columns’ keyword does not need to be passed for a Pandas series.
Colors are generated from color brewer (https://colorbrewer2.org/) sequential palettes. By default, linear binning is used between the min and the max of the values. Custom binning can be achieved with the bins parameter.
TopoJSONs can be passed as “geo_data”, but the “topojson” keyword must also be passed with the reference to the topojson objects to convert. See the topojson.feature method in the TopoJSON API reference: https://github.com/topojson/topojson/wiki/API-Reference
Parameters
- geo_data (string/object) – URL, file path, or data (json, dict, geopandas, etc) to your GeoJSON geometries
- data (Pandas DataFrame or Series, default None) – Data to bind to the GeoJSON.
- columns (dict or tuple, default None) – If the data is a Pandas DataFrame, the columns of data to be bound. Must pass column 1 as the key, and column 2 the values.
- key_on (string, default None) – Variable in the geo_data GeoJSON file to bind the data to. Must start with ‘feature’ and be in JavaScript objection notation. Ex: ‘feature.id’ or ‘feature.properties.statename’.
- bins (int or sequence of scalars or str, default 6) – If bins is an int, it defines the number of equal-width bins between the min and the max of the values. If bins is a sequence, it directly defines the bin edges. For more information on this parameter, have a look at numpy.histogram function.
- fill_color (string, optional) – Area fill color, defaults to blue. Can pass a hex code, color name, or if you are binding data, one of the following color brewer palettes: ‘BuGn’, ‘BuPu’, ‘GnBu’, ‘OrRd’, ‘PuBu’, ‘PuBuGn’, ‘PuRd’, ‘RdPu’, ‘YlGn’, ‘YlGnBu’, ‘YlOrBr’, and ‘YlOrRd’.
- nan_fill_color (string, default 'black') – Area fill color for nan or missing values. Can pass a hex code, color name.
- fill_opacity (float, default 0.6) – Area fill opacity, range 0-1.
- nan_fill_opacity (float, default fill_opacity) – Area fill opacity for nan or missing values, range 0-1.
- line_color (string, default 'black') – GeoJSON geopath line color.
- line_weight (int, default 1) – GeoJSON geopath line weight.
- line_opacity (float, default 1) – GeoJSON geopath line opacity, range 0-1.
- legend_name (string, default empty string) – Title for data legend.
- topojson (string, default None) – If using a TopoJSON, passing “objects.yourfeature” to the topojson keyword argument will enable conversion to GeoJSON.
- smooth_factor (float, default None) – How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation. Leaflet defaults to 1.0.
- highlight (boolean, default False) – Enable highlight functionality when hovering over a GeoJSON area.
- use_jenks (bool, default False) – Use jenkspy to calculate bins using “natural breaks” (Fisher-Jenks algorithm). This is useful when your data is unevenly distributed.
- name (string, optional) – The name of the layer, as it will appear in LayerControls
- overlay (bool, default True) – Adds the layer as an optional overlay (True) or the base layer (False).
- control (bool, default True) – Whether the Layer will be included in LayerControls.
- show (bool, default True) – Whether the layer will be shown on opening (only for overlays).
ReturnsReturn type
GeoJSON data layer in obj.template_vars
Examples
>>> Choropleth(geo_data="us-states.json", line_color="blue", line_weight=3)
>>> Choropleth(
... geo_data="geo.json",
... data=df,
... columns=["Data 1", "Data 2"],
... key_on="feature.properties.myvalue",
... fill_color="PuBu",
... bins=[0, 20, 30, 40, 50, 60],
... )
>>> Choropleth(geo_data="countries.json", topojson="objects.countries")
>>> Choropleth(
... geo_data="geo.json",
... data=df,
... columns=["Data 1", "Data 2"],
... key_on="feature.properties.myvalue",
... fill_color="PuBu",
... bins=[0, 20, 30, 40, 50, 60],
... highlight=True,
... )
* 실습해보기
- geo_data는 지도에 사용될 지리정보 데이터들의 집합을 넣어주면 된다. 현재 내가 넣은 'geo_data'는 JSON 형태의 파일임.
- data에는 geo_data 에서 바인딩할 실제 데이터들을 넣어주면 된다. 현재 내가 넣은 파일은 서울시 자치구별로 그룹핑한 치킨집 갯수 데이터이다.
- columns는 data가 판다스 DataFrame이면 bar차트처럼 열과 행을 구분해줘야한다. 순서는 바차트와 동일하게 1컬럼에는 index(key), 2컬럼에는 실제 value가 들어가면 된다.
- fill_color에는 ‘BuGn’, ‘BuPu’, ‘GnBu’, ‘OrRd’, ‘PuBu’, ‘PuBuGn’, ‘PuRd’, ‘RdPu’, ‘YlGn’, ‘YlGnBu’, ‘YlOrBr’, and ‘YlOrRd’. 여러 종류가 있다.
- 투명도 조절은 fill_opacity를 이용하면 된다. 0-1까지의 값을 가지며 낮아질수록 투명도가 올라간다.
- key_on은 geo_data 제이슨 파일의 변수를 지정 (columns의 변수와 일치하도록) 해주기 위한 파라미터이다.
만약 이런식으로 나열된 제이슨 파일이 있고, 내가 원하는 변수는 '송파구'라면
{'type': 'Feature',
'properties': {'code': '11240',
'name': '송파구',
'name_eng': 'Songpa-gu',
'base_year': '2013'},
'geometry': {'type': 'Polygon',
'coordinates': [[[127.0690698130372, 37.522279423505026],
[127.0690698130372, 37.522279423505026]]]}},
feature.properties.name가 key_on에 들어가야 한다.
- 선 굵기조절은 line_weight를 이용하자.
뭐 대충 이런느낌..
역시 모를 땐 공식 도큐먼트 찾아보는게 제일 빠르다.