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

View source

Data Visualization

As a data scientist, you likely perform data exploration on nearly every project. Exploratory data analysis can entail many things, from finding relevant data and cleaning it to running analysis and building models. The ability to visually analyze and interact with data is key during the exploratory process and the final presentation of insights.

With that in mind, this guide introduces the basic building blocks for creating web-based, dynamic, and interactive map visualizations inside a Jupyter Notebook with CARTOframes. A Map can display one or several Layers. Each Layer can render local data or remote data from a CARTO account with a specific style and UI elements like legends, widgets or popups.

In this guide you will be introduced to the Map and Layer classes. You will learn how to explore data with Widgets and Popups, how to use visualization styles to quickly symbolize thematic attributes and how to share your findings by publishing your visualizations. For further learning you can also check out the Data Visualization examples.

Visualize data from a file

CARTOframes allows creating maps directly with data from GeoJSON or CSV files (with geometric data).

1
2
3
from geopandas import read_file

points_gdf = read_file('http://libs.cartocdn.com/cartoframes/samples/starbucks_brooklyn_geocoded.geojson')
1
2
3
from cartoframes.viz import Layer

Layer(points_gdf)

If the source, instead of a GeoJSON, is a CSV file with a column containing the geometry encoded in WKB/WKT, you can pass the name of the column as geom_col directly to the Layer and the geometry is automatically decoded.

1
2
3
4
from pandas import read_csv

polygons_df = read_csv('http://libs.cartocdn.com/cartoframes/samples/starbucks_brooklyn_iso_enriched.csv')
polygons_gdf = read_file('http://libs.cartocdn.com/cartoframes/samples/starbucks_brooklyn_iso_enriched.geojson')
1
2
3
4
5
6
from cartoframes.viz import Map

Map([
    Layer(polygons_df, geom_col='the_geom'),
    Layer(points_gdf)
])

Visualize data from CARTO

For big datasets visualization (>30MB), we recommend rendering layers directly from a CARTO account. This, in addition to improving the performance, allows you to apply SQL queries to the tables stored in CARTO.

Note: You’ll need your CARTO Account credentials to perform this action.

1
2
3
from cartoframes.auth import set_default_credentials

set_default_credentials('cartoframes')
1
2
3
4
5
Map([
    Layer('countries'),
    Layer('SELECT * FROM global_power_plants WHERE capacity_mw > 1000'),
    Layer('world_rivers')
])

Map configuration

The map basemap and initial viewport can be customized. CARTO provides out-of-the-box basemaps: positron, voyager and darkmatter, but it also supports any URL to load external basemaps.

1
2
3
4
5
6
from cartoframes.viz import basemaps

Map(
    basemap=basemaps.voyager,
    viewport={'zoom': 13.5, 'lat': 40.4353, 'lng': -79.9916}
)

Data-driven styling

CARTOframes provides out of the box style helpers for different kinds of data-driven visualizations:

  • Basic
  • Color: bins, category, continuous
  • Size: bins, category, continuous
  • Animation

Style helpers contain built-in cartography styling. However, each method provides lots of parameters to adjust your visualization to your needs (color, size, stroke, color palette, classification methods, etc.). There are also legends, popups, and widgets. By default, only the legend and popup hover are enabled.

1
2
3
4
5
6
from cartoframes.viz import size_continuous_style

Layer(
    points_gdf,
    size_continuous_style('revenue')
)
1
2
3
4
5
6
7
8
from cartoframes.viz import Layer, color_bins_style

Layer(
    'eng_wales_pop',
    color_bins_style('pop_sq_km', palette='mint', bins=5, opacity=0.8),
    default_widget=True,
    default_popup_hover=False
)

Legends

Legends are aligned with style helpers. Each style helper contains what we call the “default legend” based on the style:

  • Basic
  • Color: bins, category, continuous
  • Size: bins, category, continuous

Depending on the geometry of the visualization (points, lines, polygons), the legend will render the corresponding symbology. Legends are also customizable, you can edit the title or add a description or a footer.

When having multiple layers in a map, legends will stack according to the order of the layers.

1
2
3
4
5
6
7
8
9
10
11
from cartoframes.viz import size_continuous_style, size_continuous_legend  # or just default_legend

Layer(
    points_gdf,
    size_continuous_style('revenue', size_range=[10,50], stroke_color='turquoise', stroke_width=2, opacity=0),
    legends=size_continuous_legend(
        title='Annual Revenue',
        description='Revenue in dollars ($)',
        footer='Source: <a href="https://www.starbucks.com/">Starbucks</a>'
    )
)

Interactive widgets

There are several widgets:

  • Formula
  • Histogram
  • Category
  • Time-series
  • Animation

Widgets interactivity is bidirectional: filtering the widgets affects the visualization and the other widgets, and when the viewport of the visualization changes, the widgets show the information filtered by viewport (unless the flag is_global is set).

1
2
3
4
5
6
7
8
9
10
11
from cartoframes.viz import formula_widget, category_widget, histogram_widget

Layer(
    polygons_gdf,
    widgets=[
        formula_widget('popcy', 'sum', 'Population'),
        formula_widget('inccymedhh', 'sum', 'Median Income Average', is_global=True),
        histogram_widget('educybach', 'Education'),
        category_widget('id_store', 'Store ID')
    ]
)

Click and hover popups

Popups are a nice tool to explore your data in a map. CARTOframes provides full customization to both click and hover popups. Using the helper popup_element you can display any property from your data.

When there are multiple layers in a map, popups will stack according to the order of the layers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from cartoframes.viz import popup_element

Layer(
    polygons_gdf,
    popup_hover=[
        popup_element('popcy', 'Population')
    ],
    popup_click=[
        popup_element('popcy', 'Population'),
        popup_element('id_store', 'Store ID'),
        popup_element('inccymedhh', 'Median Income'),
        popup_element('lbfcyempl', 'Employed Population'),
    ]
)

Grid layout

Using the Layout class we can show different maps side-to-side, for example, to compare variables for the same visualization. These grid maps can also be rendered as static by setting the is_static parameter.

1
2
3
4
5
6
from cartoframes.viz import Layout

Layout([
    Map(Layer(polygons_gdf, style=color_bins_style('inccymedhh', bins=7, palette='mint', stroke_width=0))),
    Map(Layer(polygons_gdf, style=color_bins_style('popcy', palette='pinkyl', stroke_width=0)))
], 2, 1, map_height=400, is_static=True)

Publish and share

CARTOframes allows to publish visualizations rendering local data (GeoDataFrame) and also public and private tables from CARTO accounts. The Map class provides a method to publish a map in a static URL to share it with others. Maps can be published also in “protected” mode using a password in case you don’t want to make it public.

Note: You’ll need your CARTO Account credentials to perform this action.

1
2
3
from cartoframes.auth import set_default_credentials

set_default_credentials('creds.json')
1
map_viz = Map(Layer('countries'))
1
2
3
4
map_viz.publish(
    name='countries',
    password='1234',
    if_exists='replace')
1
2
3
4
{'id': 'dcb4ebde-998c-4f98-b44d-ae790c59845e',
 'url': 'https://cartoframes-org.carto.com/u/cartoframes/kuviz/dcb4ebde-998c-4f98-b44d-ae790c59845e',
 'name': 'countries',
 'privacy': 'password'}