Map Workflows

There are two methods for creating maps in cartoframes: maps based on vector data using the CARTO VL library or maps based on raster data by using CARTO’s Static Maps API and CARTO.js library. All maps can be exported as files or displayed interactively in a Jupyter notebook.

Interactive CARTO VL Maps

Interactive CARTO VL maps are the recommended way to create maps in cartoframes. These maps have a powerful API which exposes many features of the CARTO VL mapping library, including automatic legend generation. With the use of the helper functions, maps are created with great cartographic defaults out-of-the-box and include legends and popups automatically.

class cartoframes.viz.Map(layers=None, basemap='Positron', bounds=None, size=None, viewport=None, default_legend=False, show_info=None, **kwargs)
Parameters:
  • layers (list of Layer) – List of layers. Zero or more of Layer.
  • basemap (str, optional) –
    • if a str, name of a CARTO vector basemap. One of positron, voyager, or darkmatter from the BaseMaps class, or a hex value, rgb string, or other color expression from CARTO VL.
    • if a dict, Mapbox or other style as the value of the style key. If a Mapbox style, the access token is the value of the token key.
  • bounds (dict or list, optional) – a dict with east, north, west, south properties, or a list of floats in the following order: [west, south, east, north]. If not provided the bounds will be automatically calculated to fit all features.
  • size (tuple, optional) – a (width, height) pair for the size of the map. Default is (1024, 632).
  • viewport (dict, optional) – Properties for display of the map viewport. Keys can be bearing or pitch.
  • default_legend (bool, optional) – Default False. If True, a legend will display for each layer.
  • show_info (bool, optional) – Whether to display center and zoom information in the map or not. It is False by default.

Examples

Basic usage.

from cartoframes.auth import set_default_context
from cartoframes.viz import Map, Layer

set_default_context(
    base_url='https://your_user_name.carto.com',
    api_key='your api key'
)

Map(Layer('table in your account'))

Display more than one layer on a map.

from cartoframes.auth import set_default_context
from cartoframes.viz import Map, Layer

set_default_context(
    base_url='https://your_user_name.carto.com',
    api_key='your api key'
)

Map(layers=[
    Layer('table1'),
    Layer('table2')
])

Change the CARTO basemap style.

from cartoframes.auth import set_default_context
from cartoframes.viz import Map, Layer, basemaps

set_default_context(
    base_url='https://your_user_name.carto.com',
    api_key='your api key'
)

Map(
    Layer('table in your account'),
    basemaps.darkmatter
)

Choose a custom basemap style. Here we use the Mapbox streets style, which requires an access token.

from cartoframes.auth import set_default_context
from cartoframes.viz import Map, Layer

set_default_context(
    base_url='https://your_user_name.carto.com',
    api_key='your CARTO API key'
)

basemap = {
    'style': 'mapbox://styles/mapbox/streets-v9',
    'token': 'your Mapbox token'
}

Map(
    Layer('table in your account'),
    basemap
)

Remove basemap and show a custom color.

from cartoframes.auth import set_default_context
from cartoframes.viz import Map, Layer

set_default_context(
    base_url='https://your_user_name.carto.com',
    api_key='your api key'
)

Map(
    Layer('table in your account'),
    basemap='yellow'  # None, False, 'white', 'rgb(255, 255, 0)'
)

Set custom bounds.

from cartoframes.auth import set_default_context
from cartoframes.viz import Map, Layer

set_default_context(
    base_url='https://your_user_name.carto.com',
    api_key='your api key'
)

bounds = {
    'west': -10,
    'east': 10,
    'north': -10,
    'south': 10
}

Map(
    Layer('table in your account'),
    bounds=bounds
)

Show the map center and zoom value on the map (lower left-hand corner).

from cartoframes.auth import Context, set_default_context
from cartoframes.viz import Map, Layer

context = Context(
    base_url='https://your_user_name.carto.com',
    api_key='your api key'
)
set_default_context(context)

Map(Layer('table in your account'), show_info=True)
publish(name, maps_api_key='default_public', context=None, password=None)

Publish the map visualization as a CARTO custom visualization (aka Kuviz).

Parameters:
  • name (str) – The Kuviz name on CARTO
  • maps_api_key (str, optional) – A Regular API key with permissions to Maps API and datasets used by the map
  • context (Context, optional) – Context that is associated with datasets used by the map. If set_default_context is previously used, this value will be implicitly filled in.
  • password (str, optional) – setting it your Kuviz will be protected by password. When someone will try to show the Kuviz, the password will be requested

Example

Publishing the map visualization

from cartoframes.viz import Map, Layer

tmap = Map(Layer('tablename'))
tmap.publish('Custom Map Title')
sync_data(table_name, context=None)

Synchronize datasets used by the map with CARTO.

Parameters:
  • table_name (str) – Desired table name for the dataset on CARTO. If name does not conform to SQL naming conventions, it will be ‘normalized’ (e.g., all lower case, adding _ in place of spaces and other special characters.
  • context (Context, optional) – Context that is associated with datasets used by the map. If set_default_context is previously used, this value will be implicitly filled in.
delete_publication()

Delete the published map Kuviz.

update_publication(name, password, maps_api_key='default_public', context=None)

Update the published map Kuviz.

Parameters:
  • name (str) – The Kuviz name on CARTO
  • password (str) – setting it your Kuviz will be protected by password and using None the Kuviz will be public
  • maps_api_key (str, optional) – A Regular API key with permissions to Maps API and datasets used by the map
  • context (Context, optional) – Context that is associated with datasets used by the map. If set_default_context is previously used, this value will be implicitly filled in.
static all_publications(context=None)

Get all map Kuviz published by the current user.

Parameters:context (Context, optional) – Context that is associated with user account. If set_default_context is previously used, this value will be implicitly filled in.

Helper Functions

Map helper functions bootstrap the process of creating common types of maps. These functions save time by giving great out-of-the-box cartography, legends, and popups. The layer can be further customized using optional overrides.

cartoframes.viz.helpers.color_bins_layer(source, value, title='', bins=5, palette=None)

Helper function for quickly creating a classed color map

Parameters:
  • source (Dataset or str) – Dataset or text representing a table or query associated with user account.
  • value (str) – Column to symbolize by
  • title (str, optional) – Title of legend
  • bins (int, optional) – Number of classes (bins) for map. Default is 5.
  • palette (str, optional) – Palette that can be a named cartocolor palette or other valid CARTO VL palette expression. Default is purpor.
Returns:

Layer styled by value. Includes Legend and popup on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.color_category_layer(source, value, title='', top=11, cat=None, palette='bold')

Helper function for quickly creating a category color map.

Parameters:
  • source (Dataset or str) – Dataset or text representing a table or query associated with user account.
  • value (str) – Column to symbolize by
  • title (str, optional) – Title of legend
  • top (int, optional) – Number of category for map. Default is 11. Values can range from 1 to 16.
  • cat (str, optional) – Category list. Must be a valid CARTO VL category list.
  • palette (str, optional) – Palette that can be a named cartocolor palette or other valid CARTO VL palette expression. Default is bold.
Returns:

Layer styled by value. Includes Legend and popup on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.color_continuous_layer(source, value, title='', palette=None)

Helper function for quickly creating a continuous color map

Parameters:
  • source (Dataset or str) – Dataset or text representing a table or query associated with user account.
  • value (str) – Column to symbolize by
  • title (str, optional) – Title of legend
  • palette (str, optional) – Palette that can be a named cartocolor palette or other valid CARTO VL palette expression. Default is bluyl.
Returns:

Layer styled by value. Includes Legend and popup on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.size_bins_layer(source, value, title='', bins=5, size=None, color=None)

Helper function for quickly creating a size symbol map with classification method/buckets.

Parameters:
  • source (Dataset or str) – Dataset or text representing a table or query associated with user account.
  • value (str) – Column to symbolize by
  • title (str, optional) – Title of legend
  • bins (int, optional) – Number of size classes (bins) for map. Default is 5.
  • size (str, optiona) – Min/max size array in CARTO VL syntax. Default is ‘[2, 14]’ for point geometries and ‘[1, 10]’ for lines.
  • color (str, optional) – Hex value, rgb expression, or other valid CARTO VL color. Default is ‘#EE5D5A’ for point geometries and ‘#4CC8A3’ for lines.
Returns:

Layer styled by value. Includes Legend and popup on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.size_category_layer(source, value, title='', top=5, cat=None, size=None, color=None)

Helper function for quickly creating a size category layer.

Parameters:
  • source (Dataset or str) – Dataset or text representing a table or query associated with user account.
  • value (str) – Column to symbolize by
  • title (str, optional) – Title of legend
  • top (int, optional) – Number of size categories for layer. Default is 5. Valid values range from 1 to 16.
  • cat (str, optional) – Category list. Must be a valid CARTO VL category list.
  • size (str, optiona) – Min/max size array in CARTO VL syntax. Default is ‘[2, 20]’ for point geometries and ‘[1, 10]’ for lines.
  • color (str, optional) – Hex value, rgb expression, or other valid CARTO VL color. Default is ‘#F46D43’ for point geometries and ‘#4CC8A3’ for lines.
Returns:

Layer styled by value. Includes Legend and popup on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.size_continuous_layer(source, value, title='', size=None, color=None)

Helper function for quickly creating a size symbol map with continuous size scaled by value.

Parameters:
  • source (Dataset or str) – Dataset or text representing a table or query associated with user account.
  • value (str) – Column to symbolize by
  • title (str, optional) – Title of legend
  • size (str, optiona) – Min/max size array in CARTO VL syntax. Default is ‘[2, 40]’ for point geometries and ‘[1, 10]’ for lines.
  • color (str, optional) – Hex value, rgb expression, or other valid CARTO VL color. Defaults is ‘#FFB927’ for point geometries and ‘#4CC8A3’ for lines.
Returns:

Layer styled by value. Includes Legend and popup on value.

Return type:

cartoframes.viz.Layer

Vector Layers

class cartoframes.viz.Layer(source, style=None, popup=None, legend=None, context=None)
Parameters:
  • source (str, Dataset) – The source data.
  • style (str, dict, Style, optional) – The style of the visualization: CARTO VL styling <https://carto.com/developers/carto-vl/guides/style-with-expressions/>.
  • popup (dict, Popup, optional) – This option adds interactivity (click and hover) to a layer to show popups. The columns to be shown must be added in a list format for each event. It must be written using CARTO VL expressions syntax <https://carto.com/developers/carto-vl/reference/#cartoexpressions>.
  • legend (dict, Legend, optional) – The legend definition for a layer. It contains the information to show a legend “type” (color-category, color-bins, color-continuous), “prop” (color) and also text information: “title”, “description” and “footer”.
  • context (Context) – A Context instance. This is only used for the simplified Source API. When a Source is pased as source, this context is simply ignored. If not provided the context will be automatically obtained from the default context.

Example

from cartoframes.auth import set_default_context
from cartoframes.viz import Layer

set_default_context(
    base_url='https://your_user_name.carto.com',
    api_key='your api key'
)

Layer(
    'SELECT * FROM populated_places WHERE adm0name = 'Spain'',
    'color: ramp(globalQuantiles($pop_max, 5), reverse(purpor))',
    popup={
        'hover': '$name',
        'click': ['$name', '$pop_max', '$pop_min']
    },
    legend={
        'type': 'color-category',
        'title': 'Population'
    }
)

Setting the context.

from cartoframes.auth import Context
from cartoframes.viz import Layer

context = Context(
    base_url='https://your_user_name.carto.com',
    api_key='your api key'
)

Layer(
    'populated_places',
    'color: "red"',
    context=context
)

Interactive CARTO.js Maps

CARTOframes also supports interactive and static maps based on raster tiles. The static outputs are matplotlib axes, so they can be added to subplots to accompany charts and other maps. The interactive maps are HTML documents that display in a notebook or can be exported.

CartoContext.map(layers=None, interactive=True, zoom=None, lat=None, lng=None, size=(800, 400), ax=None)

Produce a CARTO map visualizing data layers.

Examples

Create a map with two data Layers, and one BaseMap layer:

import cartoframes
from cartoframes import Layer, BaseMap, styling
cc = cartoframes.CartoContext(BASEURL, APIKEY)
cc.map(layers=[BaseMap(),
               Layer('acadia_biodiversity',
                     color={'column': 'simpson_index',
                            'scheme': styling.tealRose(7)}),
               Layer('peregrine_falcon_nest_sites',
                     size='num_eggs',
                     color={'column': 'bird_id',
                            'scheme': styling.vivid(10))],
       interactive=True)

Create a snapshot of a map at a specific zoom and center:

cc.map(layers=Layer('acadia_biodiversity',
                    color='simpson_index'),
       interactive=False,
       zoom=14,
       lng=-68.3823549,
       lat=44.3036906)
Parameters:
  • layers (list, optional) –

    List of zero or more of the following:

    • Layer: cartoframes Layer object for visualizing data from a CARTO table. See Layer for all styling options.
    • BaseMap: Basemap for contextualizng data layers. See BaseMap for all styling options.
    • QueryLayer: Layer from an arbitrary query. See QueryLayer for all styling options.
  • interactive (bool, optional) – Defaults to True to show an interactive slippy map. Setting to False creates a static map.
  • zoom (int, optional) – Zoom level of map. Acceptable values are usually in the range 0 to 19. 0 has the entire earth on a single tile (256px square). Zoom 19 is the size of a city block. Must be used in conjunction with lng and lat. Defaults to a view to have all data layers in view.
  • lat (float, optional) – Latitude value for the center of the map. Must be used in conjunction with zoom and lng. Defaults to a view to have all data layers in view.
  • lng (float, optional) – Longitude value for the center of the map. Must be used in conjunction with zoom and lat. Defaults to a view to have all data layers in view.
  • size (tuple, optional) – List of pixel dimensions for the map. Format is (width, height). Defaults to (800, 400).
  • ax – matplotlib axis on which to draw the image. Only used when interactive is False.
Returns:

Interactive maps are rendered as HTML in an iframe, while static maps are returned as matplotlib Axes objects or IPython Image.

Return type:

IPython.display.HTML or matplotlib Axes

Raster Layers

class cartoframes.layer.BaseMap(source='voyager', labels='back', only_labels=False)

Layer object for adding basemaps to a cartoframes map.

Example

Add a custom basemap to a cartoframes map.

import cartoframes
from cartoframes import BaseMap, Layer
cc = cartoframes.CartoContext(BASEURL, APIKEY)
cc.map(layers=[BaseMap(source='light', labels='front'),
               Layer('acadia_biodiversity')])
Parameters:
  • source (str, optional) – One of light or dark. Defaults to voyager. Basemaps come from https://carto.com/location-data-services/basemaps/
  • labels (str, optional) – One of back, front, or None. Labels on the front will be above the data layers. Labels on back will be underneath the data layers but on top of the basemap. Setting labels to None will only show the basemap.
  • only_labels (bool, optional) – Whether to show labels or not.
class cartoframes.layer.Layer(table_name, source=None, overwrite=False, time=None, color=None, size=None, opacity=None, tooltip=None, legend=None)

A cartoframes Data Layer based on a specific table in user’s CARTO database. This layer class is used for visualizing individual datasets with CartoContext.map’s layers keyword argument.

Example

import cartoframes
from cartoframes import QueryLayer, styling
cc = cartoframes.CartoContext(BASEURL, APIKEY)
cc.map(layers=[Layer('fantastic_sql_table',
                     size=7,
                     color={'column': 'mr_fox_sightings',
                            'scheme': styling.prism(10)})])
Parameters:
  • table_name (str) – Name of table in CARTO account
  • Styling – See QueryLayer
  • a full list of all arguments arguments for styling this map data (for) –
  • layer.
  • source (pandas.DataFrame, optional) – Not currently implemented
  • overwrite (bool, optional) – Not currently implemented
class cartoframes.layer.QueryLayer(query, time=None, color=None, size=None, opacity=None, tooltip=None, legend=None)

cartoframes data layer based on an arbitrary query to the user’s CARTO database. This layer class is useful for offloading processing to the cloud to do some of the following:

  • Visualizing spatial operations using PostGIS and PostgreSQL, which is the database underlying CARTO
  • Performing arbitrary relational database queries (e.g., complex JOINs in SQL instead of in pandas)
  • Visualizing a subset of the data (e.g., SELECT * FROM table LIMIT 1000)

Used in the layers keyword in CartoContext.map.

Example

Underlay a QueryLayer with a complex query below a layer from a table. The QueryLayer is colored by the calculated column abs_diff, and points are sized by the column i_measure.

import cartoframes
from cartoframes import QueryLayer, styling
cc = cartoframes.CartoContext(BASEURL, APIKEY)
cc.map(layers=[QueryLayer('''
                          WITH i_cte As (
                            SELECT
                                ST_Buffer(the_geom::geography, 500)::geometry As the_geom,
                                cartodb_id,
                                measure,
                                date
                              FROM interesting_data
                             WHERE date > '2017-04-19'
                          )
                          SELECT
                             i.cartodb_id, i.the_geom,
                             ST_Transform(i.the_geom, 3857) AS the_geom_webmercator,
                             abs(i.measure - j.measure) AS abs_diff,
                             i.measure AS i_measure
                            FROM i_cte AS i
                            JOIN awesome_data AS j
                              ON i.event_id = j.event_id
                           WHERE j.measure IS NOT NULL
                             AND j.date < '2017-04-29'
                          ''',
                          color={'column': 'abs_diff',
                                 'scheme': styling.sunsetDark(7)},
                          size='i_measure'),
               Layer('fantastic_sql_table')])
Parameters:
  • query (str) – Query to expose data on a map layer. At a minimum, a query needs to have the columns cartodb_id, the_geom, and the_geom_webmercator for the map to display. Read more about queries in CARTO’s docs.
  • time (dict or str, optional) –

    Time-based style to apply to layer.

    If time is a str, it must be the name of a column which has a data type of datetime or float.

    from cartoframes import QueryLayer
    l = QueryLayer('SELECT * FROM acadia_biodiversity',
                   time='bird_sighting_time')
    

    If time is a dict, the following keys are options:

    • column (str, required): Column for animating map, which must be of type datetime or float.
    • method (str, optional): Type of aggregation method for operating on Torque TileCubes. Must be one of avg, sum, or another PostgreSQL aggregate functions with a numeric output. Defaults to count.
    • cumulative (bool, optional): Whether to accumulate points over time (True) or not (False, default)
    • frames (int, optional): Number of frames in the animation. Defaults to 256.
    • duration (int, optional): Number of seconds in the animation. Defaults to 30.
    • trails (int, optional): Number of trails after the incidence of a point. Defaults to 2.
    from cartoframes import Layer
    l = Layer('acadia_biodiversity',
              time={
                  'column': 'bird_sighting_time',
                  'cumulative': True,
                  'frames': 128,
                  'duration': 15
              })
    
  • color (dict or str, optional) –

    Color style to apply to map. For example, this can be used to change the color of all geometries in this layer, or to create a graduated color or choropleth map.

    If color is a str, there are two options:

    • A column name to style by to create, for example, a choropleth map if working with polygons. The default classification is quantiles for quantitative data and category for qualitative data.
    • A hex value or web color name.
    # color all geometries red (#F00)
    from cartoframes import Layer
    l = Layer('acadia_biodiversity',
              color='red')
    
    # color on 'num_eggs' (using defalt color scheme and quantification)
    l = Layer('acadia_biodiversity',
              color='num_eggs')
    

    If color is a dict, the following keys are options, with values described:

    • column (str): Column used for the basis of styling
    • scheme (dict, optional): Scheme such as styling.sunset(7) from the styling module of cartoframes that exposes CARTOColors. Defaults to mint scheme for quantitative data and bold for qualitative data. More control is given by using styling.scheme.

      If you wish to define a custom scheme outside of CARTOColors, it is recommended to use the styling.custom utility function.

    from cartoframes import QueryLayer, styling
    l = QueryLayer('SELECT * FROM acadia_biodiversity',
                   color={
                       'column': 'simpson_index',
                       'scheme': styling.mint(7, bin_method='equal')
                   })
    
  • size (dict or int, optional) –

    Size style to apply to point data.

    If size is an int, all points are sized by this value.

    from cartoframes import QueryLayer
    l = QueryLayer('SELECT * FROM acadia_biodiversity',
                   size=7)
    

    If size is a str, this value is interpreted as a column, and the points are sized by the value in this column. The classification method defaults to quantiles, with a min size of 5, and a max size of 5. Use the dict input to override these values.

    from cartoframes import Layer
    l = Layer('acadia_biodiversity',
              size='num_eggs')
    

    If size is a dict, the follow keys are options, with values described as:

    • column (str): Column to base sizing of points on
    • bin_method (str, optional): Quantification method for dividing data range into bins. Must be one of the methods in BinMethod (excluding category).
    • bins (int, optional): Number of bins to break data into. Defaults to 5.
    • max (int, optional): Maximum point width (in pixels). Setting this overrides range. Defaults to 25.
    • min (int, optional): Minimum point width (in pixels). Setting this overrides range. Defaults to 5.
    • range (tuple or list, optional): a min/max pair. Defaults to [1, 5] for lines and [5, 25] for points.
    from cartoframes import Layer
    l = Layer('acadia_biodiversity',
              size={
                  'column': 'num_eggs',
                  'max': 10,
                  'min': 2
              })
    
  • opacity (float, optional) – Opacity of layer from 0 to 1. Defaults to 0.9.
  • tooltip (tuple, optional) – Not yet implemented.
  • legendNot yet implemented.
Raises:
  • CartoException – If a column name used in any of the styling options is not in the data source in query (or table if using Layer).
  • ValueError – If styling using a dict and a column key is not present, or if the data type for a styling option is not supported. This is also raised if styling by a geometry column (i.e., the_geom or the_geom_webmercator). Futher, this is raised if requesting a time-based map with a data source that has geometries other than points.