CARTOframes

A Python package for integrating CARTO maps, analysis, and data services into data science workflows.

CARTOframes API Reference

Introduction

The CARTOframes API is organized in three parts: auth, data, and viz.

Authentication

It is possible to use CARTOframes without having a CARTO account. However, to have access to data enrichment or to discover useful datasets, being a CARTO user offers many advantages. This module is the responsible for connecting the user with its CARTO account through given user credentials.

Manage Data

From discovering and enriching data to applying data analyisis and geocoding methods, CARTOframes API is built with the purpose of managing data without leaving the context of your notebook.

Visualize Data

The viz API is designed to create useful, beautiful and straight forward visualizations. It is at the same time predefined and flexible, in order to give advanced users the possibility of building specific visualizations, but also to offer multiple built-in methods to work faster with a few lines of code.

Auth

Auth namespace contains the class to manage authentication: Credentials. It also includes the utility functions cartoframes.auth.set_default_credentials() and cartoframes.auth.get_default_credentials().

class cartoframes.auth.Credentials(username=None, api_key='default_public', base_url=None, session=None)

Bases: object

Credentials class for managing and storing user CARTO credentials. The arguments are listed in order of precedence: Credentials instances are first, key and base_url/username are taken next, and config_file (if given) is taken last. The config file is cartocreds.json by default. If no arguments are passed, then there will be an attempt to retrieve credentials from a previously saved session. One of the above scenarios needs to be met to successfully instantiate a Credentials object.

Parameters:
  • api_key (str, optional) – API key of user’s CARTO account. If the dataset is public, it can be set to ‘default_public’.
  • username (str, optional) – Username of CARTO account
  • base_url (str, optional) – Base URL used for API calls. This is usually of the form https://johnsmith.carto.com/ for user johnsmith. On premises installations (and others) have a different URL pattern.
  • session (requests.Session, optional) – requests session. See requests documentation for more information.

Example

Setting basic credentials:

from cartoframes.auth import Credentials
credentials = Credentials(username='johnsmith', api_key='abcdefg')
api_key

Credentials api_key

base_url

Credentials base_url

classmethod delete(config_file=None)

Deletes the credentials file specified in config_file. If no file is specified, it deletes the default user credential file (cartocreds.json)

Parameters:config_file (str) – Path to configuration file. Defaults to delete the user default location if None.

Tip

To see if there is a default user credential file stored, do the following:

>>> credentials = Credentials.from_file()
>>> print(credentials)
Credentials(username='johnsmith', api_key='abcdefg', base_url='https://johnsmith.carto.com/')
classmethod from_credentials(credentials)

Retrives credentials from another Credentials object

classmethod from_file(config_file=None, session=None)

Retrives credentials from a file. Defaults to the user config directory

get_do_token()

Returns the Data Observatory v2 token

save(config_file=None)

Saves current user credentials to user directory.

Parameters:config_file (str, optional) – Location where credentials are to be stored. If no argument is provided, it will be send to the default location.

Example

from cartoframes.auth import Credentials
credentials = Credentials(username='johnsmith', api_key='abcdefg')
credentials.save()  # save to default location
from cartoframes.auth import Credentials
credentials = Credentials(username='johnsmith', api_key='abcdefg')
credentials.save('path/to/credentials/file')
session

Credentials session

username

Credentials username

cartoframes.auth.set_default_credentials(first=None, second=None, credentials=None, username=None, base_url=None, api_key=None, session=None)

Set default credentials for all operations that require authentication against a CARTO account. CARTOframes methods cartoframes.viz.Layer (and helper layers in cartoframes.viz.helpers), cartoframes.data.Dataset, cartoframes.data.clients.SQLClient, and others.

Parameters:
  • credentials (Credentials, optional) – A Credentials instance can be used in place of a username | base_url/api_key combination.
  • base_url (str, optional) – Base URL of CARTO user account. Cloud-based accounts should use the form https://{username}.carto.com (e.g., https://johnsmith.carto.com for user johnsmith) whether on a personal or multi-user account. On-premises installation users should ask their admin.
  • api_key (str, optional) – CARTO API key. Depending on the application, this can be a project API key or the account master API key.
  • username (str, optional) – CARTO user name of the account.
  • session (requests.Session, optional) – requests session. See requests documentation for more information.

Note

The recommended way to authenticate in CARTOframes is to read user credentials from a JSON file that is structured like this:

{
    "username": "your user name",
    "api_key": "your api key",
    "base_url": "https://your_username.carto.com"
}

Note that the ``base_url`` will be different for on premises installations.

By using the cartoframes.auth.Credentials.save() method, this file will automatically be created for you in a default location depending on your operating system. A custom location can also be specified as an argument to the method.

This file can then be read in the following ways:

from cartoframes.auth import Credentials, set_default_credentials

# attempts to read file from default location if it exists
creds = Credentials.from_file()

# read credentials from specified location
creds = Credentials.from_file('./carto-project-credentials.json')

# set default credentials from file
set_default_credentials(Credentials.from_file())

Example

Create Credentials from a username, api_key pair.

from cartoframes.auth import set_default_credentials

set_default_credentials(
    username='johnsmith',
    api_key='your api key'
)

# or

set_default_credentials(
    'johnsmith',
    'your api key'
)

Create credentials from only a username (only works with public datasets and those marked public with link). If the API key is not provided, the public API key default_public is used. With this setting, only read-only operations can occur (e.g., no publishing of maps, reading data from the Data Observatory, or creating new hosted datasets).

from cartoframes.auth import set_default_credentials
set_default_credentials('johnsmith')

From a pair base_url, api_key.

from cartoframes.auth import set_default_credentials
set_default_credentials(
    base_url='https://johnsmith.carto.com',
    api_key='your api key'
)
# or
set_default_credentials(
    'https://johnsmith.carto.com',
    'your api key'
)

From a base_url (for public datasets). The API key default_public is used by default.

from cartoframes.auth import set_default_credentials
set_default_credentials('https://johnsmith.carto.com')

From a Credentials class.

from cartoframes.auth import Credentials, set_default_credentials
credentials = Credentials(
    base_url='https://johnsmith.carto.com',
    api_key='your api key'
)
set_default_credentials(credentials)
cartoframes.auth.get_default_credentials()

Retrieve the default credentials if previously set with cartoframes.auth.set_default_credentials() in Python session.

Example

Retrieve default credentials.

from cartoframes.auth import set_default_credentials, get_default_credentials

set_default_credentials(Credentials.from_file())

current_creds = get_default_credentials()
Returns:Default credentials previously set in current Python session. None will returned if default credentials were not previously set.
Return type:cartoframes.auth.Credentials

Data Management

class cartoframes.data.Dataset(data, credentials=None, schema=None)

Generic data class for cartoframes data operations. A Dataset instance can be created from a dataframe, geodataframe, a table hosted on a CARTO account, an arbitrary query against a CARTO account, or a local or hosted GeoJSON source. If hosted, the data can be retrieved as a pandas DataFrame. If local or as a query, a new table can be created in a CARTO account off of the Dataset instance.

Examples

Dataframe:

import pandas
from cartoframes.data import Dataset

df = pandas.read_csv('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv')
ds = Dataset(df)

GeoDataframe:

import geopandas as gpd
from cartoframes.data import Dataset

gdf = gpd.read_file('https://opendata.arcgis.com/datasets/9485c26e98c6450e9611a2360ece965d_0.geojson')
ds = Dataset(gdf)

GeoJSON file:

from cartoframes.data import Dataset

ds = Dataset('path/to/geojson/file.geojson')

Table from CARTO:

from cartoframes.auth import set_default_credentials
from cartoframes.data import Dataset

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

ds = Dataset('table_name')

Query against tables in user CARTO account:

from cartoframes.auth import set_default_credentials
from cartoframes.data import Dataset

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

ds = Dataset('SELECT * FROM table_name JOIN table2 ON ...')
compute_geom_type()

Compute the geometry type from the data

credentials

Dataset’s Credentials

Returns:Credentials, if any, for data associated with Dataset instance.
Return type:Credentials
dataframe

Dataset dataframe

dataset_info

DatasetInfo associated with Dataset instance

Note

This method only works for Datasets created from tables.

Example

from cartoframes.auth import set_default_credentials
from cartoframes.data import Dataset

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

d = Dataset('tablename')
d.dataset_info
delete()

Delete table on CARTO account associated with a Dataset instance

Example

from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials

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

d = Dataset('table_name')
d.delete()
Returns:True if deletion is successful, False otherwise.
Return type:bool
download(limit=None, decode_geom=False, retry_times=3)

Download / read a Dataset (table or query) from CARTO account associated with the Dataset’s instance of Credentials.

Parameters:
  • limit (int, optional) – The number of rows of the Dataset to download. Default is to download all rows. This value must be >= 0.
  • decode_geom (bool, optional) – Decode Dataset geometries into Shapely geometries from EWKB encoding.
  • retry_times (int, optional) – Number of time to retry the download in case it fails. Default is 3.

Example

from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials

# use cartoframes example account
set_default_credentials('https://cartoframes.carto.com')

d = Dataset('brooklyn_poverty')
df = d.download(decode_geom=True)
exists()

Checks to see if table exists

get_column_names(exclude=None)

Get column names from a dataset

get_geodataframe()

Converts DataFrame into GeoDataFrame if possible

get_num_rows()

Get the number of rows in the dataset

get_query()

Get the computed query

get_table_names()

Get table names used by Dataset instance

is_local()

Checks if the Dataset is local (DataFrameDataset)

is_public()

Checks to see if table or table used by query has public privacy

is_remote()

Checks if the Dataset is local (TableDataset or QueryDataset)

query

Dataset query

schema

Dataset schema

table_name

Dataset table name. If None, then the data is a query or DataFrame

update_dataset_info(privacy=None, table_name=None)

Update/change Dataset privacy and name

Parameters:
  • privacy (str, optional) – One of Dataset.PRIVACY_PRIVATE, Dataset.PRIVACY_PUBLIC or Dataset.PRIVACY_LINK
  • table_name (str, optional) – Name of the dataset on CARTO. After updating it, the table_name will be changed too.

Example

from cartoframes.data import Dataset, DatasetInfo
from cartoframes.auth import set_default_credentials

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

d = Dataset('tablename')
d.update_dataset_info(privacy=Dataset.PRIVACY_LINK)
upload(with_lnglat=None, if_exists='fail', table_name=None, schema=None, credentials=None)

Upload Dataset to CARTO account associated with credentials.

Parameters:
  • with_lnglat (tuple, optional) – Two columns that have the longitude and latitude information. If used, a point geometry will be created upon upload to CARTO. Example input: (‘long’, ‘lat’). Defaults to None.
  • if_exists (str, optional) – Behavior for adding data from Dataset. Options are Dataset.IF_EXISTS_FAIL, Dataset.IF_EXISTS_REPLACE, or Dataset.IF_EXISTS_APPEND. Defaults to ‘fail’, which means that the Dataset instance will not overwrite a table of the same name if it exists. If the table does not exist, it will be created.
  • 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.
  • credentials (Credentials, optional) – credentials of user account to send Dataset to. If not provided, a default credentials (if set with set_default_credentials) will attempted to be used.

Example

Send a pandas DataFrame to CARTO:

from cartoframes.auth import set_default_credentials
from cartoframes.data import Dataset
import pandas as pd

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

df = pd.DataFrame({
    'lat': [40, 45, 50],
    'lng': [-80, -85, -90]
})

d = Dataset(df)
d.upload(with_lnglat=('lng', 'lat'), table_name='sample_table')

Data Observatory

With CARTOframes it is possible to enrich your data by using our Data Observatory Catalog through the enrichment methods.

Important: The new Data Observatory 2.0 is accessible to selected CARTO Enterprise users in a private beta. We’re still open to more beta testers, so if you’re interested, please get in touch.

class cartoframes.data.observatory.Catalog

Bases: object

Data Observatory Catalog

categories

Get all the categories in the Catalog.

Returns:CatalogList
category(category_id)

Add a category filter to the current Catalog instance.

Parameters:category_id (str) – Id value of the category to be used for filtering the Catalog.
Returns:Catalog
clear_filters()

Remove the current filters from this Catalog instance.

countries

Get all the countries in the Catalog.

Returns:CatalogList
country(country_id)

Add a country filter to the current Catalog instance.

Parameters:country_id (str) – Id value of the country to be used for filtering the Catalog.
Returns:Catalog
datasets

Get all the datasets in the Catalog.

Returns:CatalogList
datasets_filter(filter_dataset)

Get all the datasets in the Catalog filtered :returns: Datasets

geographies

Get all the geographies in the Catalog.

Returns:CatalogList
geography(geography_id)

Add a geography filter to the current Catalog instance.

Parameters:geography_id (str) – Id or slug value of the geography to be used for filtering the Catalog
Returns:Catalog
provider(provider_id)

Add a provider filter to the current Catalog instance

Parameters:provider_id (str) – Id value of the provider to be used for filtering the Catalog.
Returns:CatalogList
subscriptions(credentials=None)

Get all the subscriptions in the Catalog

Parameters:credentials (Credentials, optional) – credentials of CARTO user account. If not provided, a default credentials (if set with set_default_credentials) will be used.
Returns:CatalogDatasets
class cartoframes.data.observatory.Category(data)

Bases: cartoframes.data.observatory.catalog.entity.CatalogEntity

datasets
entity_repo = <cartoframes.data.observatory.catalog.repository.category_repo.CategoryRepository object>
geographies
name
class cartoframes.data.observatory.Country(data)

Bases: cartoframes.data.observatory.catalog.entity.CatalogEntity

categories
datasets
entity_repo = <cartoframes.data.observatory.catalog.repository.country_repo.CountryRepository object>
geographies
class cartoframes.data.observatory.CatalogDataset(data)

Bases: cartoframes.data.observatory.catalog.entity.CatalogEntity

category
country
counts()
data_source
describe()
description
download(credentials=None)

Download Dataset data.

Parameters:credentials (Credentials, optional) – credentials of CARTO user account. If not provided, a default credentials (if set with set_default_credentials) will be used.
entity_repo = <cartoframes.data.observatory.catalog.repository.dataset_repo.DatasetRepository object>
fields_by_type()
geography
geom_coverage()
classmethod get_all(filters=None, credentials=None)
classmethod get_datasets_spatial_filtered(filter_dataset)
head()
is_public_data
language
name
provider
subscribe(credentials=None)

Subscribe to a Dataset.

Parameters:credentials (Credentials, optional) – credentials of CARTO user account. If not provided, a default credentials (if set with set_default_credentials) will be used.
subscription_info(credentials=None)

Get the subscription information of a Dataset.

Parameters:credentials (Credentials, optional) – credentials of CARTO user account. If not provided, a default credentials (if set with set_default_credentials) will be used.
summary
tail()
temporal_aggregation
time_coverage
update_frequency
variables
variables_groups
version
class cartoframes.data.observatory.Geography(data)

Bases: cartoframes.data.observatory.catalog.entity.CatalogEntity

country
datasets
description
download(credentials=None)

Download Geography data.

Parameters:credentials (Credentials, optional) – credentials of CARTO user account. If not provided, a default credentials (if set with set_default_credentials) will be used.
entity_repo = <cartoframes.data.observatory.catalog.repository.geography_repo.GeographyRepository object>
geom_coverage
classmethod get_all(filters=None, credentials=None)
is_public_data
language
name
provider
subscribe(credentials=None)

Subscribe to a Geography.

Parameters:credentials (Credentials, optional) – credentials of CARTO user account. If not provided, a default credentials (if set with set_default_credentials) will be used.
subscription_info(credentials=None)

Get the subscription information of a Geography.

Parameters:credentials (Credentials, optional) – credentials of CARTO user account. If not provided, a default credentials (if set with set_default_credentials) will be used.
summary
update_frequency
version
class cartoframes.data.observatory.Provider(data)

Bases: cartoframes.data.observatory.catalog.entity.CatalogEntity

datasets
entity_repo = <cartoframes.data.observatory.catalog.repository.provider_repo.ProviderRepository object>
name
class cartoframes.data.observatory.Variable(data)

Bases: cartoframes.data.observatory.catalog.entity.CatalogEntity

agg_method
column_name
counts()
dataset
dataset_name
datasets
db_type
describe()
description
entity_repo = <cartoframes.data.observatory.catalog.repository.variable_repo.VariableRepository object>
head()
histogram()
name
project_name
quantiles()
schema_name
starred
summary
tail()
top_values()
variable_group
cartoframes.data.observatory.enrich_points(data, variables, data_geom_column='geometry', filters={}, credentials=None)

Enrich a points dataset

This method allows you to enrich your dataset with columns from our data, intersecting your points with our geographies. Extra columns as area and population will be provided with the aims of normalize these columns.

Parameters:
  • data (Dataset, DataFrame, GeoDataFrame) – a Dataset, DataFrame or GeoDataFrame object to be enriched.
  • variables (Variable, CatalogList, list, str) – variable(s), discovered through Catalog, for enriching the data argument.
  • data_geom_column (str) – string indicating the 4326 geometry column in data.
  • filters (dict, optional) – dictionary with either a column key with the name of the column to filter or a value value with the value to filter by. Filters will be used using the AND operator
  • credentials (Credentials, optional) – credentials of user account. If not provided, a default credentials (if set with set_default_credentials) will attempted to be used.
Returns:

A dataframe as the provided one but with the variables to enrich appended to it

Note that if the geometry of the data you provide intersects with more than one geometry in the enrichment dataset, the number of rows of the returned dataframe could be different than the data argument number of rows.

Examples

Enrich a points dataset with Catalog classes:

from data.observatory import enrichment
from cartoframes.auth import set_default_credentials
set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

variables = Catalog().country('usa').category('demographics').datasets[0].variables
dataset_enrich = enrichment.enrich_points(dataset, variables)

Enrich a points dataset with list of ids:

from data.observatory import enrichment
from cartoframes.auth import set_default_credentials

set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

variables = [
    'carto-do-public-data.acsquantiles.demographics_acsquantiles_usa_schooldistrictelementaryclipped_2015_5yrs_20062010.in_grades_1_to_4_quantile',
    'carto-do-public-data.acsquantiles.demographics_acsquantiles_usa_schooldistrictelementaryclipped_2015_5yrs_20062010.in_school_quantile'
]

dataset_enrich = enrichment.enrich_points(dataset, variables)

Enrich a points dataset filtering our data:

from data.observatory import enrichment
from cartoframes.auth import set_default_credentials

set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

variables = Catalog().country('usa').category('demographics').datasets[0].variables
filters = {'do_date': '2019-09-01'}
dataset_enrich = enrichment.enrich_points(dataset, variables, filters)
cartoframes.data.observatory.enrich_polygons(data, variables, agg_operators={}, data_geom_column='geometry', filters={}, credentials=None)

Enrich a polygons dataset

This method allows you to enrich your dataset with columns from our data, intersecting your polygons with our geographies. When a polygon intersects with multiple geographies of our dataset, the proportional part of the intersection will be used to interpolate the quantity of the polygon value intersected, aggregating them with the operator provided by agg_operators argument.

Parameters:
  • data (Dataset, DataFrame, GeoDataFrame) – a Dataset, DataFrame or GeoDataFrame object to be enriched.
  • variables (Variable, CatalogList, list, str) – variable(s), discovered through Catalog, for enriching the data argument.
  • agg_operators (dict, str, None, optional) – dictionary with either a column key with the name of the column to aggregate or a operator value with the operator to group by. If agg_operators’ dictionary is empty (default argument value) then aggregation operators will be retrieved from metadata column. If agg_operators is a string then all columns will be aggregated by this operator. If agg_operators is None then no aggregations will be computed. All the values which data geometry intersects with will be returned.
  • data_geom_column (str) – string indicating the 4326 geometry column in data.
  • filters (dict, optional) – dictionary with either a column key with the name of the column to filter or a value value with the value to filter by.
  • credentials (Credentials, optional) – credentials of user account. If not provided, a default credentials (if set with set_default_credentials) will attempted to be used.
Returns:

A dataframe as the provided one but with the variables to enrich appended to it

Note that if the geometry of the data you provide intersects with more than one geometry in the enrichment dataset, the number of rows of the returned dataframe could be different than the data argument number of rows.

Examples

Enrich a polygons dataset with Catalog classes and default aggregation methods:

from data.observatory import enrichment
from cartoframes.auth import set_default_credentials

set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

variables = Catalog().country('usa').category('demographics').datasets[0].variables

dataset_enrich = enrichment.enrich_polygons(dataset, variables)

Enrich a polygons dataset with list of ids:

from data.observatory import enrichment
from cartoframes.auth import set_default_credentials

set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

variables = [
    'carto-do-public-data.acsquantiles.demographics_acsquantiles_usa_schooldistrictelementaryclipped_2015_5yrs_20062010.in_grades_1_to_4_quantile',
    'carto-do-public-data.acsquantiles.demographics_acsquantiles_usa_schooldistrictelementaryclipped_2015_5yrs_20062010.in_school_quantile'
]

dataset_enrich = enrichment.enrich_polygons(dataset, variables)

Enrich a polygons dataset filtering our data:

from data.observatory import enrichment
from cartoframes.auth import set_default_credentials

set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

variables = Catalog().country('usa').category('demographics').datasets[0].variables
filters = {'do_date': '2019-09-01'}

dataset_enrich = enrichment.enrich_polygons(dataset, variables, filters)

Enrich a polygons dataset with custom aggregation methods:

from data.observatory import enrichment
from cartoframes.auth import set_default_credentials

set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

variables = [
    'carto-do-public-data.acsquantiles.demographics_acsquantiles_usa_schooldistrictelementaryclipped_2015_5yrs_20062010.in_grades_1_to_4_quantile',
    'carto-do-public-data.acsquantiles.demographics_acsquantiles_usa_schooldistrictelementaryclipped_2015_5yrs_20062010.in_school_quantile'
]

agg_operators = {'in_grades_1_to_4_quantile': 'SUM', 'in_school_quantile': 'AVG'}
dataset_enrich = enrichment.enrich_polygons(dataset, variables, agg_operators=agg_operators)

Enrich a polygons dataset with no aggregation methods:

from data.observatory import enrichment
from cartoframes.auth import set_default_credentials

set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

variables = [
    'carto-do-public-data.acsquantiles.demographics_acsquantiles_usa_schooldistrictelementaryclipped_2015_5yrs_20062010.in_grades_1_to_4_quantile',
    'carto-do-public-data.acsquantiles.demographics_acsquantiles_usa_schooldistrictelementaryclipped_2015_5yrs_20062010.in_school_quantile'
]

agg_operators = None
dataset_enrich = enrichment.enrich_polygons(dataset, variables, agg_operators=agg_operators)

Data Services

Geocoding

The cartoframes.data.services.Geocoding class provides geocoding using CARTO Location Data Services (LDS) This process requires you to have a CARTO account with a geocoding provider and geocoding quota assigned, and its use will incur in the expense of geocoding credits. In the case of accounts with soft geocoding limits, additional charges may apply if the monthly quota is exceeded.

The Geocoding.geocode instance method provides the interface to geocoding; input data to be geocoded must be provided through a Dataset or DataFrame object as the first argument to this method.

A second mandatory argument, street defines the name of the data column that contains the street address.

Additional optional arguments can be used to define the city, state and country. These arguments can be used to either pass the name of a column that contains the corresponding attribute; e.g. city={'column': 'column_name_of_the_city'}, which can be shortened as city='column_name_of_the_city', or, when all the dataset corresponds to a single value of the attribute, a literal text, e.g. city={'value': 'London}'.

For each geocoded record, some status information is available, as described in https://carto.com/developers/data-services-api/reference/

Name Type Description
precision text precise or interpolated
relevance number 0 to 1, higher being more relevant
match_types array list of match type strings point_of_interest, country, state, county, locality, district, street, intersection, street_number, postal_code

By default the relevance is stored in an output column named gc_status_rel. The name of the column and in general what attributes are added as columns can be configured by using a status dictionary associating column names to status attribute.

The result of the geocode method is a named tuple containing both a result data (of same class as the input, Dataframe``or ``Dataframe) and a metadata dictionary with general information about the process.

Dry run

To find out the number of quota credits that will be spent when geocoding a dataset pass a dry_run=True argument:

from cartoframes.data.services import Geocoding
from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials

set_default_credentials(
    username='YOUR_USERNAME',
    api_key='YOUR_APIKEY'
)
gc = Geocoding()

dataset = Dataset('YOUR_DATA')
info = gc.geocode(dataset, street='address', city='city', country={'value': 'Spain'}, dry_run=True).metadata
print(info.get('required_quota'))

When dry_run is True no changes will be made to the data and no quota will be consumed. The returned dataset will simply be a reference to the input dataset, unmodified.

To know the quota available in the account used, the method available_quota can be used:

print(gc.available_quota())

Geocoding Dataframes

A Dataframe can be geocoded like this:

import pandas
from cartoframes.data.services import Geocoding
from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials

set_default_credentials(
    username='YOUR_USERNAME',
    api_key='YOUR_APIKEY'
)
gc = Geocoding()

df = pandas.DataFrame([['Gran Vía 46', 'Madrid'], ['Ebro 1', 'Sevilla']], columns=['address', 'city'])

geocoded_dataframe, info = gc.geocode(df, street='address', city='city', country={'value': 'Spain'})
print(info)
print(geocoded_dataframe)
# Filtering by relevance
print(geocoded_dataframe[geocoded_dataframe['gc_status_rel']>0.7])

To specify the status attributes and column names explicitly use the status argument:

geocoded_dataframe, info = gc.geocode(df, street='address', city='city', country={'value': 'Spain'}, status={'relev':'relevance'})
print(geocoded_dataframe[geocoded_dataframe['relev']>0.7])

To store the results permanently in a CARTO dataset the argument table_name can be used:

# ...
geocoded_dataset, info = gc.geocode(df, street='address', city='city', country={'value': 'Spain'}, table_name='new_table')
print(info)
print(geocoded_dataset.download())

Geocoding Tables

When the Dataset to be geocoded corresponds to a CARTO table, it will by default be modified in place:

import pandas
from cartoframes.data.services import Geocoding
from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials

set_default_credentials(
    username='YOUR_USERNAME',
    api_key='YOUR_APIKEY'
)
gc = Geocoding()

dataset = Dataset('YOUR_DATA')
dataset, info = gc.geocode(dataset, street='address', country={'value': 'Spain'})
print(info)
print(dataset.download())

To leave the existing table unmodified and place the results in a new table the table_name argument can be used:

# ...
dataset = Dataset('YOUR_DATA')
new_dataset, info = gc.geocode(dataset, street='address', country={'value': 'Spain'}, table_name='new_table')
print(info)
print(new_dataset.download())

Geocoding Queries

When the Dataset to be geocoded corresponds to a query, it will by default be geocoded into a new dataframe dataset:

import pandas
from cartoframes.data.services import Geocoding
from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials

set_default_credentials(
    username='YOUR_USERNAME',
    api_key='YOUR_APIKEY'
)
gc = Geocoding()

dataset = Dataset('SELECT * FROM YOUR_DATA WHERE value>1000')
geocoded_dataset, info = gc.geocode(dataset, street='address', city='city', country={'value': 'Spain'})
print(info)
print(geocoded_dataset.dataframe)

Again, the results can be stored in a new table using the table_name argument:

# ...
dataset = Dataset('SELECT * FROM YOUR_DATA WHERE value>1000')
new_dataset, info = gc.geocode(dataset, street='address', country={'value': 'Spain'}, table_name='new_table')
print(info)
print(new_dataset.download())

Saving Quota

To prevent having to geocode records that have been previously geocoded, and thus spend quota unnecessarily, you should always preserve the the_geom and carto_geocode_hash columns generated by the geocoding process. This will happen automatically if your input is a table Dataset processed in place (i.e. without a table_name parameter) or if you save your results in a CARTO table using the table_name parameter, and only use the resulting table for any further geocoding.

In case you’re geocoding local data from a DataFrame that you plan to re-geocode again, (e.g. because you’re making your work reproducible by saving all the data preparation steps in a notebook), we advise to save the geocoding results immediately to the same store from when the data is originally taken, for example:

dataframe = pandas.read_csv('my_data')
dataframe = Geocoding().geocode(dataframe, 'address').data
dataframe.to_csv('my_data')

As an alternative you can use the cached option to store geocoding results in a CARTO table and reuse them in later geocodings. The parameter is the name of the table used to cache the results, and can be used with dataframe or query datasets.

dataframe = pandas.read_csv('my_data')
dataframe = Geocoding().geocode(dataframe, 'address', cached='my_data').data

If you execute the previous code multiple times it will only spend credits on the first geocoding; later ones will reuse the results stored in the my_data table. This will require extra processing time. If the csv file should ever change, cached results will only be applied to unmodified records, and new geocoding will be performed only on new or changed records.

Isolines

The cartoframes.data.services.Isolines class provides time and distance isolines using CARTO Location Data Services (LDS)

This use these functions a CARTO account is required with a geocoding provider and geocoding quota assigned. Its use will incur in the expense of geocoding credits. In the case of accounts with soft geocoding limits, additional charges may apply if the monthly quota is exceeded.

Isodistance and Isochrone areas

These two operations compute areas that are within a given range (as a travel time or distance) of a central or source point. Isochrones correspond to the area that can be reached within a given time in seconds from the source point traveling through the roads network using the specified modality (either walking or by car). Isodistances are base instead in travel distance as specified in meters.

There are two methods isochrones and isodistances, both taking the same parameters and returning similar values.

Two of the arguments in these methods are mandatory: the source and the ranges.

The source is a dataset which contains the points to be taken as the origins of the travel areas. Separate areas will be computed for each source point.

The ranges argument is an array of numbers, each of one specifying either a distance in meters (for isodistances) or a time in seconds (for isochrones). An individual area will be compute for each source point and range value.

The resulting dataset will include a the_geom column with the resulting area and a data_range numeric column with the corresponding range value. Optionally a source_id column identifying the source point can be included, which is useful if the source dataset cotains cartodb_id identifiers.

The computed polygons represent the whole area reachable within the specified time or distance from its source point (if the is_destination option is used, routes are computed to the source points instead).

This implies that the areas corresponding to larger range values will completely include within them the areas corresponding to smaller range values. If you intend to visualize the resulting areas by representing them on a map it may be complicated to avoid larger areas obscuring the smaller ones.

For these reason an alternative outcome, better suited for map representation is also provided by using the exclusive argument; when this is True, exclusive range areas are produced instead of inclusive range areas. In exclusive mode, for each range value, computed polygons will represent the area within an interval of times (or distances) between the next lower range, if any, as a mininum time/distance, and the maximum value. In this manner, the produced areas for a given source point do not overlap, each one representing an exclusive interval of times or distances. In this case an additional lower_data_range column will represent the minimun range value in the area. This will be zero in the case of the areas corresponding to the smaller range value.

Note that computing exclusive areas will require a longer processing time.

Return value

The result is a tuple composed of two named entries: data containing the result areas and metadata containing additional information.

The data component is a Dataframe or a Dataset depending on the kind of source input. The other, metadata, is a dictionary.

The table_name argument, when used, forces the result to be saved as a CARTO table. When this argurment is used an additional argument if_exists can be used to determine the behaviour when the table name already exists in the CARTO account. Possible values are:

  • fail (the default) will yield an error if the table exists
  • replace is used to replace existing tables
  • append adds the new data to an existing table
Additional parameters
  • mode with possible values 'car' and 'walk' defines the travel mode.
  • is_destination (False/True) indicates that the input points are to be consider destinations for the routes used to compute the area, rather than origins.
  • mode_type type of routes computed: 'shortest' (default) or 'fastests'.
  • mode_traffic use traffic data to compute routes: 'disabled' (default) or 'enabled'.
  • resolution level of detail of the polygons in meters per pixel. Higher resolution may increase the response time of the service.
  • maxpoints Allows to limit the amount of points in the returned polygons. Increasing the number of maxpoints may increase the response time of the service.
  • quality (1/2/3) Allows you to reduce the quality of the polygons in favor of the response time.

Dry run

To find out the number of quota credits that will be spent when computing isochrone or isodistances areas, pass a dry_run=True argument:

from cartoframes.data.services import Isolines
from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials

set_default_credentials(
    username='YOUR_USERNAME',
    api_key='YOUR_APIKEY'
)
travel = Isolines()

dataset = Dataset('YOUR_DATA')
info = travel.isochrones(dataset, ranges=[1800, 3600], dry_run=True).metadata
print(info.get('required_quota'))

When dry_run is True no areas will be computed and no quota will be consumed. The returned dataset (the data field of the result named tuple) will be None.

Converting between the exclusive and inclusive range representation

These methods are handy to convert a table from one of the representations to the other, so you can use both in your analyses and visualizations without spendit credits for the two of them.

The assume the areas are saved in a table with a cartodb_id, a source_id referencing the source points, a data_range columns for the range values and the_geom, i.e. the format created by the isochrones and isodistances methods from a source with a cartodb_id and saved to a table (table_name).

def inclusive_to_exclusive(inclusive_table_name, exclusive_table_name, if_exists='fail', credentials=None):
    sql = """
        SELECT
            cartodb_id,
            source_id,
            data_range,
            COALESCE(
                LAG(data_range, 1) OVER (PARTITION BY source_id ORDER BY data_range),
                0
            ) AS lower_data_range,
            COALESCE(
                ST_DIFFERENCE(the_geom, LAG(the_geom, 1) OVER (PARTITION BY source_id ORDER BY data_range)),
                the_geom
            ) AS the_geom
        FROM {table_name}
    """.format(table_name=inclusive_table_name)
    Dataset(sql, credentials=credentials).upload(table_name=exclusive_table_name, if_exists=if_exists)

def exclusive_to_inclusive(exclusive_table_name, inclusive_table_name, if_exists='fail', credentials=None):
    sql = """
        SELECT
            cartodb_id,
            source_id,
            data_range,
            ST_UNION(the_geom) OVER (PARTITION BY source_id ORDER BY data_range) AS the_geom
        FROM {table_name}
    """.format(table_name=exclusive_table_name)
    Dataset(sql, credentials=credentials).upload(table_name=inclusive_table_name, if_exists=if_exists)
class cartoframes.data.services.Geocoding(credentials=None)

Bases: cartoframes.data.services.service.Service

Geocoding using CARTO data services. This requires a CARTO account with and API key that allows for using geocoding services; (through explicit argument in constructor or via the default credentials). Use of these methods will incur in geocoding credit consumption for the provided account.

Examples

Obtain the number of credits needed to geocode a dataset:

from data.services import Geocoding
from cartoframes.auth import set_default_credentials
set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')
gc = Geocoding()
_, info = gc.geocode(dataset, street='address', dry_run=True)
print(info['required_quota'])

Geocode a dataframe:

import pandas
from data.services import Geocoding
from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials
set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

dataframe = pandas.DataFrame([['Gran Vía 46', 'Madrid'], ['Ebro 1', 'Sevilla']], columns=['address','city'])
gc = Geocoding()
geocoded_dataframe, info = gc.geocode(dataframe, street='address', city='city', country={'value': 'Spain'})
print(geocoded_dataframe)

Geocode a table:

import pandas
from data.services import Geocoding
from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials
set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

dataset = Dataset('YOUR_TABLE_NAME')
gc = Geocoding()
geocoded_dataset, info = gc.geocode(dataset, street='address', city='city', country={'value': 'Spain'})
print(geocoded_dataset.download())

Filter results by relevance:

import pandas
from data.services import Geocoding
from cartoframes.data import Dataset
from cartoframes.auth import set_default_credentials
set_default_credentials('YOUR_USER_NAME', 'YOUR_API_KEY')

df = pandas.DataFrame([['Gran Vía 46', 'Madrid'], ['Ebro 1', 'Sevilla']], columns=['address','city'])
gc = Geocoding()
df = gc.geocode(df, street='address', city='city', country={'value': 'Spain'}, status=['relevance']).data
# show rows with relevance greater than 0.7:
print(df[df['carto_geocode_relevance']>0.7, axis=1)])
geocode(input_data, street, city=None, state=None, country=None, status={'gc_status_rel': 'relevance'}, table_name=None, if_exists='fail', dry_run=False, cached=None)

Geocode a dataset

Parameters:
  • input_data (Dataset, DataFrame) – a Dataset or DataFrame object to be geocoded.
  • street (str) – name of the column containing postal addresses
  • city (dict, optional) – dictionary with either a column key with the name of a column containing the addresses’ city names or a value key with a literal city value value, e.g. ‘New York’. It also accepts a string, in which case column is implied.
  • state (dict, optional) – dictionary with either a column key with the name of a column containing the addresses’ state names or a value key with a literal state value value, e.g. ‘WA’. It also accepts a string, in which case column is implied.
  • country (dict, optional) – dictionary with either a column key with the name of a column containing the addresses’ country names or a value key with a literal country value value, e.g. ‘US’. It also accepts a string, in which case column is implied.
  • status (dict, optional) – dictionary that defines a mapping from geocoding state attributes (‘relevance’, ‘precision’, ‘match_types’) to column names. (See https://carto.com/developers/data-services-api/reference/) Columns will be added to the result data for the requested attributes. By default a column gc_status_rel will be created for the geocoding _relevance_. The special attribute ‘*’ refers to all the status attributes as a JSON object.
  • table_name (str, optional) – the geocoding results will be placed in a new CARTO table with this name.
  • if_exists (str, optional) – Behavior for creating new datasets, only applicable if table_name isn’t None; Options are ‘fail’, ‘replace’, or ‘append’. Defaults to ‘fail’.
  • cached (str, optional) – name of a table used cache geocoding results. Can only be used with DataFrames or queries. This parameter is not compatbile with table_name.
  • dry_run (bool, optional) – no actual geocoding will be performed (useful to check the needed quota)
Returns:

A named-tuple (data, metadata) containing either a data Dataset or DataFrame (same type as the input) and a metadata dictionary with global information about the geocoding process

The data contains a the_geom column with point locations for the geocoded addresses and also a carto_geocode_hash that, if preserved, can avoid re-geocoding unchanged data in future calls to geocode.

class cartoframes.data.services.Isolines(credentials=None)

Bases: cartoframes.data.services.service.Service

Time and distance Isoline services using CARTO dataservices.

isochrones(source, ranges, **args)

isochrone areas

This method computes areas delimited by isochrone lines (lines of constant travel time) based upon public roads.

Parameters:
  • source (Dataset, Dataframe) – containing the source points for the isochrones: travel routes from the source points are computed to determine areas within specified travel times.
  • ranges (list) – travel time values in seconds; for each range value and source point a result polygon will be produced enclosing the area within range of the source.
  • exclusive (bool, optional) – when False (the default), inclusive range areas are generated, each one containing the areas for smaller time values (so the area is reachable from the source whithin the given time). When True, areas are exclusive, each one corresponding time values between the immediately smaller range value (or zero) and the area range value,
  • table_name (str, optional) – the resulting areas will be saved in a new CARTO table with this name.
  • if_exists (str, optional) – Behavior for creating new datasets, only applicable if table_name isn’t None; Options are ‘fail’, ‘replace’, or ‘append’. Defaults to ‘fail’.
  • dry_run (bool, optional) – no actual computattion will be performed, and metadata will be returned including the required quota.
  • mode (str, optional) – defines the travel mode: 'car' (the default) or 'walk'.
  • is_destination (bool, optional) – indicates that the source points are to be taken as destinations for the routes used to compute the area, rather than origins.
  • mode_type (str, optional) – type of routes computed: 'shortest' (default) or 'fastests'.
  • mode_traffic (str, optional) – use traffic data to compute routes: 'disabled' (default) or 'enabled'.
  • resolution (float, optional) – level of detail of the polygons in meters per pixel. Higher resolution may increase the response time of the service.
  • maxpoints (int, optional) – Allows to limit the amount of points in the returned polygons. Increasing the number of maxpoints may increase the response time of the service.
  • quality – (int, optional): Allows you to reduce the quality of the polygons in favor of the response time. Admitted values: 1/2/3.
Returns:

A named-tuple (data, metadata) containing either a data Dataset or DataFrame (same type as the input source) and a metadata dictionary. For dry runs the data will be None. The data contains a range_data column with a numeric value and a the_geom geometry with the corresponding area. It will also contain a source_id column that identifies the source point corresponding to each area if the source has a cartodb_id column.

isodistances(source, ranges, **args)

isodistance areas

This method computes areas delimited by isodistance lines (lines of constant travel distance) based upon public roads.

Parameters:
  • source (Dataset, Dataframe) – containing the source points for the isochrones: travel routes from the source points are computed to determine areas within specified travel distances.
  • ranges (list) – travel distance values in meters; for each range value and source point a result polygon will be produced enclosing the area within range of the source.
  • exclusive (bool, optional) – when False (the default), inclusive range areas are generated, each one containing the areas for smaller distance values (so the area is reachable from the source whithin the given distance). When True, areas are exclusive, each one corresponding distance values between the immediately smaller range value (or zero) and the area range value,
  • table_name (str, optional) – the resulting areas will be saved in a new CARTO table with this name.
  • if_exists (str, optional) – Behavior for creating new datasets, only applicable if table_name isn’t None; Options are ‘fail’, ‘replace’, or ‘append’. Defaults to ‘fail’.
  • dry_run (bool, optional) – no actual computattion will be performed, and metadata will be returned including the required quota.
  • mode (str, optional) – defines the travel mode: 'car' (the default) or 'walk'.
  • is_destination (bool, optional) – indicates that the source points are to be taken as destinations for the routes used to compute the area, rather than origins.
  • mode_type (str, optional) – type of routes computed: 'shortest' (default) or 'fastests'.
  • mode_traffic (str, optional) – use traffic data to compute routes: 'disabled' (default) or 'enabled'.
  • resolution (float, optional) – level of detail of the polygons in meters per pixel. Higher resolution may increase the response time of the service.
  • maxpoints (int, optional) – Allows to limit the amount of points in the returned polygons. Increasing the number of maxpoints may increase the response time of the service.
  • quality – (int, optional): Allows you to reduce the quality of the polygons in favor of the response time. Admitted values: 1/2/3.
Returns:

A named-tuple (data, metadata) containing either a data Dataset or DataFrame (same type as the input source) and a metadata dictionary. For dry runs the data will be None. The data contains a range_data column with a numeric value and a the_geom geometry with the corresponding area. It will also contain a source_id column that identifies the source point corresponding to each area if the source has a cartodb_id column.

Viz

Viz namespace contains all the classes to create a visualization, mainly Map and Layer. It also includes our basemaps and the helper methods.

cartoframes.viz.basemaps

alias of Basemaps

cartoframes.viz.themes

alias of Themes

class cartoframes.viz.Map(layers=None, basemap='Positron', bounds=None, size=None, viewport=None, default_legend=False, show_info=None, theme=None, title=None, description=None, is_static=None, **kwargs)

Bases: object

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 west, south, east, north keys, or an array of floats in the following structure: [[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, it displays the map title. Therefore, it needs the title value to be defined.
  • show_info (bool, optional) – Whether to display center and zoom information in the map or not. It is False by default.
  • is_static (bool, optional) – Default False. If True, instead of showing and interactive map, a png image will be displayed.
  • theme (string, optional) – Use a different UI theme
  • title (string, optional) – Title to label the map
  • description (string, optional) – Text that describes the map and will be displayed in the default legend after the title.

Examples

Basic usage.

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

set_default_credentials(
    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_credentials
from cartoframes.viz import Map, Layer

set_default_credentials(
    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_credentials
from cartoframes.viz import Map, Layer, basemaps

set_default_credentials(
    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_credentials
from cartoframes.viz import Map, Layer

set_default_credentials(
    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_credentials
from cartoframes.viz import Map, Layer

set_default_credentials(
    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_credentials
from cartoframes.viz import Map, Layer

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

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

# or bounds = [[-10, 10], [10, -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 Credentials, set_default_credentials
from cartoframes.viz import Map, Layer

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

Map(Layer('table in your account'), show_info=True)
static all_publications(credentials=None)

Get all map Kuviz published by the current user.

Parameters:credentials (Credentials, optional) – A Credentials instance. If not provided, the credentials will be automatically obtained from the default credentials if available.
delete_publication()

Delete the published map Kuviz.

get_content()
publish(name, table_name=None, credentials=None, password=None)

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

Parameters:
  • name (str) – The Kuviz name on CARTO
  • table_name (str, optional) – Desired table name for the dataset on CARTO. It is required working with local data (we need to upload it to 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.
  • credentials (Credentials, optional) – A Credentials instance. If not provided, the credentials will be automatically obtained from the default credentials if available. It is used to create the publication and also to save local data (if exists) into your CARTO account
  • 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')
update_publication(name, password)

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
class cartoframes.viz.Layout(maps, n_size=None, m_size=None, viewport=None, map_height=250, is_static=True)

Bases: object

Create a layout of visualizations in order to compare them.

Parameters:
  • maps (list of Map) – List of maps. Zero or more of Map.
  • N_SIZE (number, optional) – Number of columns of the layout
  • M_SIZE (number, optional) – Number of rows of the layout
  • viewport (dict, optional) – Properties for display of the maps viewport. Keys can be bearing or pitch.

Examples

Basic usage.

from cartoframes.auth import set_default_credentials
from cartoframes.viz import Map, Layer, Layout

set_default_credentials('your_account')

Layout([
    Map(Layer('table_in_your_account')), Map(Layer('table_in_your_account')),
    Map(Layer('table_in_your_account')), Map(Layer('table_in_your_account'))
])

Display a 2x2 layout.

from cartoframes.auth import set_default_credentials
from cartoframes.viz import Map, Layer, Layout

set_default_credentials('your_account')

Layout([
    Map(Layer('table_in_your_account')), Map(Layer('table_in_your_account')),
    Map(Layer('table_in_your_account')), Map(Layer('table_in_your_account'))
], 2, 2)

Custom Titles.

from cartoframes.auth import set_default_credentials
from cartoframes.viz import Map, Layer, Layout

set_default_credentials('your_account')

Layout([
    Map(Layer('table_in_your_account'), title="Visualization 1 custom title"),
    Map(Layer('table_in_your_account'), title="Visualization 2 custom title")),
])

Viewport.

from cartoframes.auth import set_default_credentials
from cartoframes.viz import Map, Layer, Layout

set_default_credentials('your_account')

Layout([
    Map(Layer('table_in_your_account')),
    Map(Layer('table_in_your_account')),
    Map(Layer('table_in_your_account')),
    Map(Layer('table_in_your_account'))
], viewport={ 'zoom': 2 })
from cartoframes.auth import set_default_credentials
from cartoframes.viz import Map, Layer, Layout

set_default_credentials('your_account')

Layout([
    Map(Layer('table_in_your_account'), viewport={ 'zoom': 0.5 }),
    Map(Layer('table_in_your_account')),
    Map(Layer('table_in_your_account')),
    Map(Layer('table_in_your_account'))
], viewport={ 'zoom': 2 })
class cartoframes.viz.Layer(source, style=None, popup=None, legend=None, widgets=None, credentials=None, bounds=None)

Bases: object

Layer to display data on a map. This class can be used as one or more layers in Map or on its own in a Jupyter notebook to get a preview of a Layer.

Parameters:
  • source (str, Dataset, or pandas.DataFrame) – The source data.
  • style (str, dict, or Style, optional) – The style of the visualization: CARTO VL styling.
  • popup (dict or 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. See Popup for more information.
  • legend (dict or 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”. See Legend for more information.
  • widgets (dict, list, or WidgetList, optional) – Widget or list of widgets for a layer. It contains the information to display different widget types on the top right of the map. See WidgetList for more information.
  • credentials (Credentials) – A Credentials instance. This is only used for the simplified Source API. When a Source is pased as source, these credentials is simply ignored. If not provided the credentials will be automatically obtained from the default credentials.
  • bounds (dict or list, optional) – a dict with west, south, east, north keys, or an array of floats in the following structure: [[west, south], [east, north]]. If not provided the bounds will be automatically calculated to fit all features.

Example

Create a layer with a custom popup, legend, and widget.

from cartoframes.auth import set_default_credentials
from cartoframes.viz import Layer

set_default_credentials(
    base_url='https://cartovl.carto.com',
    api_key='default_public'
)

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'
    },
    widgets=[{
        'type': 'formula',
        'title': 'Avg $pop_max',
        'value': 'viewportAvg($pop_max)'
    }]
)

Create a layer specifically tied to a Credentials and display it on a map.

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

credentials = Credentials(
    base_url='https://cartovl.carto.com',
    api_key='default_public'
)

pop_layer = Layer(
    'populated_places',
    'color: red',
    credentials=credentials
)
Map(pop_layer)

Preview a layer in a Jupyter notebook. Note: if in a Jupyter notebook, it is not required to explicitly add a Layer to a Map if only visualizing data as a single layer.

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

set_default_credentials('https://cartoframes.carto.com')

pop_layer = Layer(
    'brooklyn_poverty',
    'color: ramp($poverty_per_pop, sunset)',
    legend={
        'type': 'color-continuous',
        'title': 'Poverty per pop'
    }
)
pop_layer
class cartoframes.viz.Source(data, credentials=None, bounds=None, schema=None)

Bases: object

Parameters:
  • (str, geopandas.GeoDataFrame, pandas.DataFrame, (data) – Dataset ): a table name, SQL query, GeoJSON file, GeoDataFrame, DataFrame, or Dataset object.
  • credentials (Credentials, optional) – A Credentials instance. If not provided, the credentials will be automatically obtained from the default credentials if available.
  • bounds (dict or list, optional) – a dict with west, south, east, north keys, or an array of floats in the following structure: [[west, south], [east, north]]. If not provided the bounds will be automatically calculated to fit all features.

Example

Table name.

from cartoframes.auth import set_default_credentials
from cartoframes.viz import Source

set_default_credentials('your_user_name', 'your api key')

Source('table_name')

SQL query.

from cartoframes.auth import set_default_credentials
from cartoframes.viz import Source

set_default_credentials('your_user_name', 'your api key')

Source('SELECT * FROM table_name')

GeoJSON file.

from cartoframes.viz import Source

Source('path/to/file.geojson')

Dataset object.

from cartoframes.viz import Source
from cartoframes.data import Dataset

set_default_credentials('your_user_name', 'your api key')

ds = Dataset('table_name')

Source(ds)

Setting the credentials.

from cartoframes.auth import Credentials
from cartoframes.viz import Source

credentials = Credentials('your_user_name', 'your api key')

Source('table_name', credentials)

Setting the bounds.

from cartoframes.auth import set_default_credentials
from cartoframes.viz import Source

set_default_credentials('your_user_name', 'your api key')

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

Source('table_name', bounds=bounds)
get_credentials()
get_geom_type()
class cartoframes.viz.Style(data=None)

Bases: object

Parameters:data (str, dict) – The style for the layer. It can be a dictionary or a viz string. More info at CARTO VL styling <https://carto.com/developers/carto-vl/guides/style-with-expressions/>

Example

String API.

from cartoframes.viz import Style

Style('color: blue')

Style('''
    @sum: sqrt($pop_max) / 100
    @grad: [red, blue, green]
    color: ramp(globalEqIntervals($pop_min, 3), @grad)
    filter: @sum > 20
''')

Dict API.

from cartoframes.viz import Style

Style({
    'color': 'blue'
})

Style({
    'vars': {
        'sum': 'sqrt($pop_max) / 100',
        'grad': '[red, blue, green]'
    },
    'color': 'ramp(globalEqIntervals($pop_min, 3), @grad)',
    'filter': '@sum > 20'
})
compute_viz(geom_type, variables={})
class cartoframes.viz.Popup(data=None)

Bases: object

Parameters:data (dict) – The popup definition for a layer. It contains the information to show a popup on ‘click’ and ‘hover’ events with the attributes provided in the definition using the CARTO VL expressions syntax <https://carto.com/developers/carto-vl/reference/#cartoexpressions>.

Example

Show columns.

from cartoframes.viz import Popup

Popup({
    'hover': ['$name'],
    'click': ['$name', '$pop_max']
})

Show expressions.

from cartoframes.viz import Popup

Popup({
    'click': ['$pop_min % 100', 'sqrt($pop_max)']
})

Show titles.

from cartoframes.viz import Popup

Popup({
    'hover': [{
        'title': 'Name',
        'value': '$name'
    }],
    'click': [{
        'title': 'Name',
        'value': '$name'
    }, {
        'title': 'Pop max',
        'value': '$pop_max'
    }]
})
get_interactivity()
get_variables()
class cartoframes.viz.Legend(f_arg, **kwargs)

Bases: object

Parameters:
  • type (str) – ‘color-category’, ‘color-bins’, ‘color-continuous’, ‘size-bins’, or ‘size-continuous’.
  • prop (str, optional) – ‘color’, ‘width’, ‘strokeColor’, or ‘strokeWidth’.
  • dynamic (boolean, optional) – Update an render the legend depending on viewport changes. Defaults to True.
  • title (str, optional) – Title of legend.
  • description (str, optional) – Description in legend.
  • footer (str, optional) – Footer of legend. This is often used to attribute data sources.
  • variable (str, optional) – If the information in the legend depends on a different value than the information set to the style property, it is possible to set an independent variable.

Example

from cartoframes.viz import Legend

Legend('color-category', title='Legend Title', 'description': '[description]', 'footer': '[footer]')
from cartoframes.viz import Layer, Legend, Style

Layer(
    "SELECT * FROM populated_places WHERE adm0name = 'Spain'",
    Style('''
        color: ramp(globalQuantiles($pop_max, 5), reverse(purpor))
        @custom_legend: ramp($pop_max, reverse(purpor))
    '''),
    legend=Legend('color-category', title='Population', variable='custom_legend')
)
get_info(geom_type=None)
class cartoframes.viz.LegendList(legends=None)

Bases: object

Parameters:legends (dict, list, Legend) – List of legends for a layer.

Example

get_info(geom_type=None)
class cartoframes.viz.Widget(f_arg, **kwargs)
Parameters:
  • type – The widget type. It can be ‘default’, ‘formula’, time-series’, ‘animation’, ‘category’, ‘histogram’.
  • value – A constant value or a CARTO VL expression.
  • title (optional) – Widget title.
  • description (optional) – Description shown below the title.
  • footer (optional) – Footer of widget. This is often used to attribute data sources.

Example:

from cartoframes.viz import Widget

Widget('formula', value='viewportSum($amount)', title='Widget Title',
       'description': '[description]', 'footer': '[footer]')
get_default_prop(data)
get_info()
has_bridge()
class cartoframes.viz.WidgetList(widgets=None)

Bases: object

Parameters:widgets (dict, list, Widget) – The list of widgets for a layer.

Example:

get_variables()
get_widgets_info()

Widgets

Widget helpers to generate widgets faster.

cartoframes.viz.widgets.animation_widget(**kwargs)

Helper function for quickly creating an animated widget. The animation widget includes an animation status bar as well as controls to play or pause animated data. The filter property of your map’s style, applied to either a date or numeric field, drives both the animation and the widget. Only one animation can be controlled per layer.

To learn more about creating animations visit:
Parameters:
  • title (str, optional) – Title of widget.
  • description (str, optional) – Description text widget placed under widget title.
  • footer (str, optional) – Footer text placed on the widget bottom
Returns:

Widget with type=’animation’

Return type:

cartoframes.viz.Widget

Example

from cartoframes.viz import Map, Layer
from cartoframes.viz.widgets import animation_widget

Map(
    Layer(
        'seattle_collisions',
        'filter: animation($incdate, 20, fade(0.5,0.5))',
        widgets=[
            animation_widget(
                title='Collision Date',
                description= 'Play, pause, or select the range of the animation'
            )]
    )
)
cartoframes.viz.widgets.category_widget(value, **kwargs)

Helper function for quickly creating a category widget.

Parameters:
  • value (str) – Column name of the category value
  • title (str, optional) – Title of widget.
  • description (str, optional) – Description text widget placed under widget title.
  • footer (str, optional) – Footer text placed on the widget bottom
  • read_only (boolean, optional) – Interactively filter a category by selecting it in the widget. Set to “False” by default.
Returns:

Widget with type=’category’

Return type:

cartoframes.viz.Widget

Example

from cartoframes.viz import Map, Layer
from cartoframes.viz.widgets import category_widget

Map(
    Layer(
        'seattle_collisions',
        widgets=[
            category_widget(
                'collisiontype',
                title='Type of Collision',
                description='Select a category to filter',
            )
        ]
    )
)
cartoframes.viz.widgets.default_widget(**kwargs)

Helper function for quickly creating a default widget.

The default widget is a general purpose widget that can be used to provide additional information about your map.

Parameters:
  • title (str, optional) – Title of widget.
  • description (str, optional) – Description text widget placed under widget title.
  • footer (str, optional) – Footer text placed on the widget bottom
Returns:

Widget with type=’default’

Return type:

cartoframes.viz.Widget

Example

from cartoframes.viz import Map, Layer
from cartoframes.viz.widgets import default_widget

Map(
    Layer(
        'seattle_collisions',
        widgets=[
            default_widget(
                title='Road Collisions in 2018',
                description='An analysis of collisions in Seattle, WA',
                footer='Data source: City of Seattle'
            )]
    )
)
cartoframes.viz.widgets.formula_widget(value, operation=None, **kwargs)

Helper function for quickly creating a formula widget.

Formula widgets calculate aggregated values (‘Avg’, ‘Max’, ‘Min’, ‘Sum’) from numeric columns or counts of features (‘Count’) in a dataset.

A formula widget’s aggregations can be calculated on ‘global’ or ‘viewport’ based values. If you want the values in a formula widget to update on zoom and/or pan, use viewport based aggregations.

Parameters:
  • value (str) – Column name of the numeric value
  • operation (str) – attribute for widget’s aggregated value (‘count’, ‘avg’, ‘max’, ‘min’, ‘sum’)
  • title (str, optional) – Title of widget.
  • description (str, optional) – Description text widget placed under widget title.
  • footer (str, optional) – Footer text placed on the widget bottom
  • is_global (boolean, optional) – Account for calculations based on the entire dataset (‘global’) vs. the default of ‘viewport’ features.
Returns:

Widget with type=’formula’

Return type:

cartoframes.viz.Widget

Example

from cartoframes.viz import Map, Layer
from cartoframes.viz.widgets import formula_widget

Map(
    Layer(
        'seattle_collisions',
        widgets=[
            formula_widget(
                'count',
                title='Number of Collisions',
                description='Zoom and/or pan the map to update count',
                footer='collisions in this view'
            )
        ]
    )
)
from cartoframes.viz import Map, Layer
from cartoframes.viz.widgets import formula_widget

Map(
    Layer(
        'seattle_collisions',
        widgets=[
            formula_widget(
                'pedcount',
                'sum',
                is_global=True,
                title='Total Number of Pedestrians',
                description='involved over all collisions',
                footer='pedestrians'
            )
        ]
    )
)
cartoframes.viz.widgets.histogram_widget(value, **kwargs)

Helper function for quickly creating a histogram widget.

Histogram widgets display the distribution of a numeric attribute, in buckets, to group ranges of values in your data. By default, you can hover over each bar to see each bucket’s values and count, and also filter your map’s data within a given range

Parameters:
  • value (str) – Column name of the numeric or date value
  • title (str, optional) – Title of widget.
  • description (str, optional) – Description text widget placed under widget title.
  • footer (str, optional) – Footer text placed on the widget bottom
  • buckets (number, optional) – Number of histogram buckets. Set to 20 by default.
  • read_only (boolean, optional) – Interactively filter a range of numeric values by selecting them in the widget. Set to “False” by default.
Returns:

Widget with type=’histogram’

Return type:

cartoframes.viz.Widget

Example

from cartoframes.viz import Map, Layer
from cartoframes.viz.widgets import histogram_widget

Map(
    Layer(
        'seattle_collisions',
        widgets=[
            histogram_widget(
                'vehcount',
                title='Number of Vehicles Involved',
                description='Select a range of values to filter',
                buckets=9
            )
        ]
    )
)
cartoframes.viz.widgets.time_series_widget(value, **kwargs)

Helper function for quickly creating a time series widget.

The time series widget enables you to display animated data (by aggregation) over a specified date or numeric field. Time series widgets provide a status bar of the animation, controls to play or pause, and the ability to filter on a range of values.

Parameters:
  • value (str) – Column name of the numeric or date value
  • title (str, optional) – Title of widget.
  • description (str, optional) – Description text widget placed under widget title.
  • footer (str, optional) – Footer text placed on the widget bottom
  • buckets (number, optional) – Number of histogram buckets. Set to 20 by default.
  • read_only (boolean, optional) – Interactively filter a range of numeric values by selecting them in the widget. Set to “False” by default.
Returns:

Widget with type=’time-series’

Return type:

cartoframes.viz.Widget

Example

from cartoframes.viz import Map, Layer
from cartoframes.viz.widgets import time_series_widget

Map(
    Layer(
        'seattle_collisions',
        'filter: animation($incdate, 20, fade(0.5,0.5))',
        widgets=[
            time_series_widget(
                value='incdate',
                title='Number of Collisions by Date',
                description= 'Play, pause, or select a range for the animation',
                buckets=10
            )]
    )
)

Helpers

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='', method='quantiles', bins=5, breaks=None, palette=None, size=None, opacity=None, stroke_color=None, stroke_width=None, description='', footer='', legend=True, popup=True, widget=False, animate=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.
  • method (str, optional) – Classification method of data: “quantiles”, “equal”, “stdev”. Default is “quantiles”.
  • bins (int, optional) – Number of size classes (bins) for map. Default is 5.
  • breaks (int[], optional) – Assign manual class break values.
  • palette (str, optional) – Palette that can be a named cartocolor palette or other valid CARTO VL palette expression. Default is purpor.
  • size (int, optional) – Size of point or line features.
  • opacity (int, optional) – Opacity value for point color and line features. Default is ‘0.8’.
  • stroke_width (int, optional) – Size of the stroke on point features.
  • stroke_color (str, optional) – Color of the stroke on point features. Default is ‘#222’.
  • description (str, optional) – Description text legend placed under legend title.
  • footer (str, optional) – Footer text placed under legend items.
  • legend (bool, optional) – Display map legend: “True” or “False”. Set to “True” by default.
  • popup (bool, optional) – Display popups on hover and click: “True” or “False”. Set to “True” by default.
  • widget (bool, optional) – Display a widget for mapped data: “True” or “False”. Set to “False” by default.
  • animate (str, optional) – Animate features by date/time or other numeric field.
Returns:

Layer styled by value. Includes a legend, popup and widget on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.color_category_layer(source, value, title='', top=11, cat=None, palette=None, size=None, opacity=None, stroke_color=None, stroke_width=None, description='', footer='', legend=True, popup=True, widget=False, animate=None)

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.
  • size (int, optional) – Size of point or line features.
  • opacity (int, optional) – Opacity value for point color and line features. Default is ‘0.8’.
  • stroke_width (int, optional) – Size of the stroke on point features.
  • stroke_color (str, optional) – Color of the stroke on point features. Default is ‘#222’.
  • description (str, optional) – Description text legend placed under legend title.
  • footer (str, optional) – Footer text placed under legend items.
  • legend (bool, optional) – Display map legend: “True” or “False”. Set to “True” by default.
  • popup (bool, optional) – Display popups on hover and click: “True” or “False”. Set to “True” by default.
  • widget (bool, optional) – Display a widget for mapped data. Set to “False” by default.
  • animate (str, optional) – Animate features by date/time or other numeric field.
Returns:

Layer styled by value. Includes a legend, popup and widget on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.color_continuous_layer(source, value, title='', palette=None, size=None, opacity=None, stroke_color=None, stroke_width=None, description='', footer='', legend=True, popup=True, widget=False, animate=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.
  • size (int, optional) – Size of point or line features.
  • opacity (int, optional) – Opacity value for point color and line features. Default is ‘0.8’.
  • stroke_width (int, optional) – Size of the stroke on point features.
  • stroke_color (str, optional) – Color of the stroke on point features. Default is ‘#222’.
  • description (str, optional) – Description text legend placed under legend title.
  • footer (str, optional) – Footer text placed under legend items.
  • legend (bool, optional) – Display map legend: “True” or “False”. Set to “True” by default.
  • popup (bool, optional) – Display popups on hover and click: “True” or “False”. Set to “True” by default.
  • widget (bool, optional) – Display a widget for mapped data. Set to “False” by default.
  • animate (str, optional) – Animate features by date/time or other numeric field.
Returns:

Layer styled by value. Includes a legend, popup and widget on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.size_bins_layer(source, value, title='', method='quantiles', bins=5, breaks=None, size=None, color=None, opacity=None, stroke_width=None, stroke_color=None, description='', footer='', legend=True, popup=True, widget=False, animate=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.
  • method (str, optional) – Classification method of data: “quantiles”, “equal”, “stdev”. Default is “quantiles”.
  • bins (int, optional) – Number of size classes (bins) for map. Default is 5.
  • breaks (int[], optional) – Assign manual class break values.
  • size (int, 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.
  • opacity (int, optional) – Opacity value for point color and line features. Default is ‘0.8’.
  • stroke_width (int, optional) – Size of the stroke on point features.
  • stroke_color (str, optional) – Color of the stroke on point features. Default is ‘#222’.
  • description (str, optional) – Description text legend placed under legend title.
  • footer (str, optional) – Footer text placed under legend items.
  • legend (bool, optional) – Display map legend: “True” or “False”. Set to “True” by default.
  • popup (bool, optional) – Display popups on hover and click: “True” or “False”. Set to “True” by default.
  • widget (bool, optional) – Display a widget for mapped data. Set to “False” by default.
  • animate (str, optional) – Animate features by date/time or other numeric field.
Returns:

Layer styled by value. Includes a legend, popup and widget on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.size_category_layer(source, value, title='', top=5, cat=None, size=None, color=None, opacity=None, stroke_width=None, stroke_color=None, description='', footer='', legend=True, popup=True, widget=False, animate=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.
  • opacity (int, optional) – Opacity value for point color and line features. Default is ‘0.8’.
  • stroke_width (int, optional) – Size of the stroke on point features.
  • stroke_color (str, optional) – Color of the stroke on point features. Default is ‘#222’.
  • description (str, optional) – Description text legend placed under legend title.
  • footer (str, optional) – Footer text placed under legend items.
  • legend (bool, optional) – Display map legend: “True” or “False”. Set to “True” by default.
  • popup (bool, optional) – Display popups on hover and click: “True” or “False”. Set to “True” by default.
  • widget (bool, optional) – Display a widget for mapped data. Set to “False” by default.
  • animate (str, optional) – Animate features by date/time or other numeric field.
Returns:

Layer styled by value. Includes a legend, popup and widget on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.size_continuous_layer(source, value, title='', size=None, color=None, opacity=None, stroke_width=None, stroke_color=None, description='', footer='', legend=True, popup=True, widget=False, animate=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.
  • opacity (int, optional) – Opacity value for point color and line features. Default is ‘0.8’.
  • stroke_width (int, optional) – Size of the stroke on point features.
  • stroke_color (str, optional) – Color of the stroke on point features. Default is ‘#222’.
  • description (str, optional) – Description text legend placed under legend title.
  • footer (str, optional) – Footer text placed under legend items.
  • legend (bool, optional) – Display map legend: “True” or “False”. Set to “True” by default.
  • popup (bool, optional) – Display popups on hover and click: “True” or “False”. Set to “True” by default.
  • widget (bool, optional) – Display a widget for mapped data. Set to “False” by default.
  • animate (str, optional) – Animate features by date/time or other numeric field.
Returns:

Layer styled by value. Includes a legend, popup and widget on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.cluster_size_layer(source, value=None, operation='count', resolution=32, title='', color=None, opacity=None, stroke_width=None, stroke_color=None, description='', footer='', legend=True, popup=True, widget=False, animate=None)

Helper function for quickly creating a cluster map with continuously sized points.

Parameters:
  • source (Dataset or str) – Dataset or text representing a table or query associated with user account.
  • value (str) – Numeric column to aggregate.
  • operation (str, optional) – Cluster operation, defaults to ‘count’. Other options available are ‘avg’, ‘min’, ‘max’, and ‘sum’.
  • resolution (int, optional) – Resolution of aggregation grid cell. Set to 32 by default.
  • title (str, optional) – Title of legend and hover.
  • color (str, optional) – Hex value, rgb expression, or other valid CARTO VL color. Defaults is ‘#FFB927’ for point geometries.
  • opacity (int, optional) – Opacity value for point color and line features. Default is ‘0.8’.
  • stroke_width (int, optional) – Size of the stroke on point features.
  • stroke_color (str, optional) – Color of the stroke on point features. Default is ‘#222’.
  • description (str, optional) – Description text legend placed under legend title.
  • footer (str, optional) – Footer text placed under legend items.
  • legend (bool, optional) – Display map legend: “True” or “False”. Set to “True” by default.
  • popup (bool, optional) – Display popups on hover and click: “True” or “False”. Set to “True” by default.
  • widget (bool, optional) – Display a widget for mapped data. Set to “False” by default.
  • animate (str, optional) – Animate features by date/time or other numeric field.
Returns:

Layer styled by value. Includes a legend, popup and widget on value.

Return type:

cartoframes.viz.Layer

cartoframes.viz.helpers.animation_layer(source, value, title='', duration=None, fade=None, size=None, color=None, opacity=None, stroke_color=None, stroke_width=None, widget_type='time-series', description='')

Helper function for quickly creating an animated 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 widget.
  • color (str, optional) – Hex value, rgb expression, or other valid CARTO VL color. Default is ‘#EE5D5A’ for point geometries, ‘#4CC8A3’ for lines and #826DBA for polygons.
  • size (int, optional) – Size of point or line features.
  • opacity (int, optional) – Opacity value for point color and line features. Default is ‘0.8’.
  • stroke_width (int, optional) – Size of the stroke on point features.
  • stroke_color (str, optional) – Color of the stroke on point features. Default is ‘#222’.
  • widget_type (str, optional) – Type of animation widget: “animation” or “time-series”. The default is “time-series”.
  • description (str, optional) – Description text placed under the widget title.
  • fade (string, optional) – Animation fade with the format: “(fade in, fade out)”. Default is (1, 1).
Returns:

Layer styled by value. Includes Widget value.

Return type:

cartoframes.viz.Layer

Exceptions

exception cartoframes.exceptions.DiscoveryException(message)

Bases: exceptions.Exception

This exception is raised when a problem is encountered while using the Catalog Discovery functions (i.e. requesting an element with an unknown ID).

exception cartoframes.exceptions.EnrichmentException(message)

Bases: exceptions.Exception

This exception is raised when a problem is encountered while using enrichment functions.