데이터분석

# 참고. Folium의 메소드들에 대해서

책다니엘 2024. 3. 29. 18:20

docstring

Jupyter Notebook에서 함수나 클래스의 기능들, 독스트링(doc string)을 확인하기 위해서는 함수나 클래스 뒤에 ()를 빼고 ?를 넣는다. 예를 들어, Folium의 Map기능의 경우 다음과 같은 내용이 표시된다.

Init signature:
folium.Map(
    location: Union[Sequence[float], NoneType] = None,
    width: Union[str, float] = '100%',
    height: Union[str, float] = '100%',
    left: Union[str, float] = '0%',
    top: Union[str, float] = '0%',
    position: str = 'relative',
    tiles: Union[str, folium.raster_layers.TileLayer, NoneType] = 'OpenStreetMap',
    attr: Union[str, NoneType] = None,
    min_zoom: int = 0,
    max_zoom: int = 18,
    zoom_start: int = 10,
    min_lat: int = -90,
    max_lat: int = 90,
    min_lon: int = -180,
    max_lon: int = 180,
    max_bounds: bool = False,
    crs: str = 'EPSG3857',
    control_scale: bool = False,
    prefer_canvas: bool = False,
    no_touch: bool = False,
    disable_3d: bool = False,
    png_enabled: bool = False,
    zoom_control: bool = True,
    font_size: str = '1rem',
    **kwargs: Union[str, float, bool, Sequence, dict, NoneType],
)
Docstring:     
Create a Map with Folium and Leaflet.js

Generate a base map of given width and height with either default
tilesets or a custom tileset URL. Folium has built-in all tilesets
available in the ``xyzservices`` package. For example, you can pass
any of the following to the "tiles" keyword:

    - "OpenStreetMap"
    - "CartoDB Positron"
    - "CartoDB Voyager"
    - "NASAGIBS Blue Marble"

You can pass a custom tileset to Folium by passing a
:class:`xyzservices.TileProvider` or a Leaflet-style
URL to the tiles parameter: ``http://{s}.yourtiles.com/{z}/{x}/{y}.png``.

You can find a list of free tile providers here:
``http://leaflet-extras.github.io/leaflet-providers/preview/``.
Be sure to check their terms and conditions and to provide attribution
with the `attr` keyword.

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 :class:`xyzservices.TileProvider`, default 'OpenStreetMap'
    Map tileset to use. Can choose from a list of built-in tiles,
    pass a :class:`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.
font_size : int or float or string (default: '1rem')
    The font size to use for Leaflet, can either be a number or a
    string ending in 'rem', 'em', or 'px'.
**kwargs
    Additional keyword arguments are passed to Leaflets Map class:
    https://leafletjs.com/reference.html#map

Returns
-------
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",
... )
File:           c:\users\kdh\miniconda3\envs\ds_study\lib\site-packages\folium\folium.py
Type:           type
Subclasses:

어떤 기능이 있는지, 어떤 식으로 작성하면 되는지, 어떤 자료형인지 나와있다. 이러한 정보들을 바탕으로 코드 작성 시에 바로 기능이 생각나지 않을 때, 새로운 라이브러리를 사용할 때 필요한 기능들을 사전처럼 검색해볼 수 있다.

 

.save('path')

path 안에 경로를 입력하면 지도를 html형태로 저장해준다. 

 

tiles option 

folium.Map() 안에 tiles= 'tiles option' 값을 넣어주면 기본적으로 built-in 되어 있는 지도의 경우 한 번에 제공해준다.

folium의 경우 다음과 같은 값을 제공해준다.

    - "OpenStreetMap"
    - "CartoDB Positron"
    - "CartoDB Voyager"
    - "NASAGIBS Blue Marble"

 

.marker()

지도에 마커를 생성해준다. 

folium.Marker(
    location: Union[Sequence[float], NoneType] = None,
    popup: Union[ForwardRef('Popup'), str, NoneType] = None,
    tooltip: Union[ForwardRef('Tooltip'), str, NoneType] = None,
    icon: Union[folium.map.Icon, NoneType] = None,
    draggable: bool = False,
    **kwargs: Union[str, float, bool, Sequence, dict, NoneType],
)

Parameters
----------
location: tuple or list
    Latitude and Longitude of Marker (Northing, Easting)
popup: string or folium.Popup, default None
    Label for the Marker; either an escaped HTML string to initialize
    folium.Popup or a folium.Popup instance.
tooltip: str or folium.Tooltip, default None
    Display a text when hovering over the object.
icon: Icon plugin
    the Icon plugin to use to render the marker.
draggable: bool, default False
    Set to True to be able to drag the marker around the map.

 

folium.Icon()

아이콘을 예쁘게 꾸며 준다.

folium.Icon(
    color: str = 'blue',
    icon_color: str = 'white',
    icon: str = 'info-sign',
    angle: int = 0,
    prefix: str = 'glyphicon',
    **kwargs: Union[str, float, bool, Sequence, dict, NoneType],
)
Docstring:     
Creates an Icon object that will be rendered
using Leaflet.awesome-markers.

Parameters
----------
color : str, default 'blue'
    The color of the marker. You can use:

        ['red', 'blue', 'green', 'purple', 'orange', 'darkred',
         'lightred', 'beige', 'darkblue', 'darkgreen', 'cadetblue',
         'darkpurple', 'white', 'pink', 'lightblue', 'lightgreen',
         'gray', 'black', 'lightgray']

icon_color : str, default 'white'
    The color of the drawing on the marker. You can use colors above,
    or an html color code.
icon : str, default 'info-sign'
    The name of the marker sign.
    See Font-Awesome website to choose yours.
    Warning : depending on the icon you choose you may need to adapt
    the `prefix` as well.
angle : int, default 0
    The icon will be rotated by this amount of degrees.
prefix : str, default 'glyphicon'
    The prefix states the source of the icon. 'fa' for font-awesome or
    'glyphicon' for bootstrap 3.

https://github.com/lvoogdt/Leaflet.awesome-markers

 

folium.ClickForMarker()

지도 위에 마우스로 클릭했을 때 마커를 생성해준다.

만들어진 지도에 .add_child()메서드를 통해 넣을 수 있고, popup()메소드를 받는다.

 

 

folium.LatLngPopup()

지도를 마우스로 클릭했을 때 위도,경도 정보를 반환해준다. ClickForMarker()과 똑같이 .add_child()메소드를 통해 적용하며, 아무 옵션도 없다.

 

folium.Circle(), folium.CircleMarker()

지도에 동그라미를 표시해준다.

 

folium.Choropleth()

지리데이터 정보를 받아 지도를 시각화해주는 메소드이다.

Init signature:
folium.Choropleth(
    geo_data: Any, # 경계선 좌표값이 담긴 데이터
    data: Union[Any, NoneType] = None, # Series or DataFrame
    columns: Union[Sequence[Any], NoneType] = None, # DataFrame Columns
    key_on: Union[str, NoneType] = None,# 위의 두 데이터를 하나의 옵션으로 묶어준다
    
    # 아래부터는 꾸며주는 옵션
    bins: Union[int, Sequence[float]] = 6,
    fill_color: Union[str, NoneType] = None,
    nan_fill_color: str = 'black',
    fill_opacity: float = 0.6,
    nan_fill_opacity: Union[float, NoneType] = None,
    line_color: str = 'black',
    line_weight: float = 1,
    line_opacity: float = 1,
    name: Union[str, NoneType] = None,
    legend_name: str = '',
    overlay: bool = True,
    control: bool = True,
    show: bool = True,
    topojson: Union[str, NoneType] = None,
    smooth_factor: Union[float, NoneType] = None,
    highlight: bool = False,
    use_jenks: bool = False,
    **kwargs,
)

 

 

이외의 기능들은 아래의 링크를 참고하면 된다.

 

https://nbviewer.jupyter.org/github/python-visualization/folium/tree/master/examples