Geoshape#
mark_geoshape represents an arbitrary shapes whose geometry is determined by specified spatial data.
Geoshape Mark Properties#
A geoshape mark can contain any standard mark properties.
Basic Map#
Altair can work with many different geographical data formats, including geojson and topojson files. Often, the most convenient input format to use is a GeoDataFrame. Here we load the Natural Earth 110m Cultural Vectors dataset and create a basic map using mark_geoshape:
import altair as alt
from altair.datasets import data
import geopandas as gpd
url = "https://naciscdn.org/naturalearth/110m/cultural/ne_110m_admin_0_countries.zip"
gdf_ne = gpd.read_file(url) # zipped shapefile
gdf_ne = gdf_ne[["NAME", "CONTINENT", "POP_EST", 'geometry']]
alt.Chart(gdf_ne).mark_geoshape()
In the example above, Altair applies a default blue fill color and uses a default map projection (equalEarth). We can customize the colors and boundary stroke widths using standard mark properties. Using the project method we can also define a custom map projection manually:
alt.Chart(gdf_ne).mark_geoshape(
fill='lightgrey', stroke='white', strokeWidth=0.5
).project(
type='albers'
)
Focus & Filtering#
By default Altair automatically adjusts the projection so that all the data fits within the width and height of the chart. Multiple approaches can be used to focus on specific regions of your spatial data. Namely:
Filter the source data within your GeoDataFrame.
Filter the source data using a
transform_filter.Specify
scale(zoom level) andtranslate(panning) within theprojectmethod.Specify
fit(extent) within theproject&clip=Truein the mark properties.
The following examples applies these approaches to focus on continental Africa:
Filter the source data within your GeoDataFrame:
gdf_sel = gdf_ne.query("CONTINENT == 'Africa'")
alt.Chart(gdf_sel).mark_geoshape()
Filter the source data using a
transform_filter:
alt.Chart(gdf_ne).mark_geoshape().transform_filter(
alt.datum.CONTINENT == 'Africa'
)
Specify
scale(zoom level) andtranslate(panning) within theprojectmethod:
alt.Chart(gdf_ne).mark_geoshape().project(
scale=200,
translate=[160, 160] # lon, lat
)
Specify
fit(extent) within theprojectmethod &clip=Truein the mark properties:
extent_roi = gdf_ne.query("CONTINENT == 'Africa'")
xmin, ymin, xmax, ymax = extent_roi.total_bounds
# fit object should be a GeoJSON-like Feature or FeatureCollection
extent_roi_feature = {
"type": "Feature",
"geometry": {"type": "Polygon",
"coordinates": [[
[xmax, ymax],
[xmax, ymin],
[xmin, ymin],
[xmin, ymax],
[xmax, ymax]]]},
"properties": {}
}
alt.Chart(gdf_ne).mark_geoshape(clip=True).project(
fit=extent_roi_feature
)
Cartesian coordinates#
The default projection of Altair is equalEarth, which accurately represents the areas of the world’s landmasses relative each other. This default assumes that your geometries are in degrees and referenced by longitude and latitude values.
Another widely used coordinate system for data visualization is the 2d cartesian coordinate system. This coordinate system does not take into account the curvature of the Earth.
In the following example the input geometry is not projected and is instead rendered directly in raw coordinates using the identity projection type. We have to define the reflectY as well since Canvas and SVG treats positive y as pointing down.
alt.Chart(gdf_sel).mark_geoshape().project(
type='identity',
reflectY=True
)
Note
When working with spatial data, it’s important to be aware of coordinate reference systems and geometry winding order. For detailed information on projections and winding order, see the Spatial Data section in the data guide.
Mapping Polygons#
The following example maps the visual property of the NAME column using the color encoding.
alt.Chart(gdf_sel).mark_geoshape().encode(
color='NAME:N'
)
Since each country is represented by a (multi)polygon, we can separate the stroke and fill definitions as such:
alt.Chart(gdf_sel).mark_geoshape(
stroke='white',
strokeWidth=1.5
).encode(
fill='NAME:N'
)
Mapping Lines#
By default Altair assumes for mark_geoshape that the mark’s color is used for the fill color instead of the stroke color.
This means that if your source data contain (multi)lines, you will have to explicitly define the filled value as False.
Compare:
gs_line = gpd.GeoSeries.from_wkt(['LINESTRING (0 0, 1 1, 0 2, 2 2, -1 1, 1 0)'])
alt.Chart(gs_line).mark_geoshape().project(
type='identity',
reflectY=True
)
With:
gs_line = gpd.GeoSeries.from_wkt(['LINESTRING (0 0, 1 1, 0 2, 2 2, -1 1, 1 0)'])
alt.Chart(gs_line).mark_geoshape(
filled=False
).project(
type='identity',
reflectY=True
)
Using this approach one can also style Polygons as if they are Linestrings:
alt.Chart(gdf_sel).mark_geoshape(
filled=False,
strokeWidth=1.5
).encode(
stroke='NAME:N'
)
Mapping Points#
Points can be drawn when they are defined as Points within a GeoDataFrame using mark_geoshape.
We first assign the centroids of Polygons as Point geometry and plot these:
# .copy() to prevent changing the original `gdf_sel` variable
# derive centroid in a projected CRS (in meters) and visualize in a geographic CRS (in degrees).
gdf_centroid = gpd.GeoDataFrame(
data=gdf_sel.copy(),
geometry=gdf_sel.geometry.to_crs(epsg=3857).centroid.to_crs(epsg=4326)
)
alt.Chart(gdf_centroid).mark_geoshape()
Caveat: To use the size encoding for the Points you will need to use the mark_circle in combination with the latitude and longitude encoding channel definitions.
gdf_centroid["lon"] = gdf_centroid.geometry.x
gdf_centroid["lat"] = gdf_centroid.geometry.y
alt.Chart(gdf_centroid).mark_circle().encode(
longitude="lon:Q", latitude="lat:Q", size="POP_EST:Q"
)
Altair also contains expressions related to geographical features. We can for example define the centroids using a geoCentroid expression:
basemap = alt.Chart(gdf_sel).mark_geoshape(
fill='lightgray', stroke='white', strokeWidth=0.5
)
bubbles = alt.Chart(gdf_sel).transform_calculate(
centroid=alt.expr.geoCentroid(None, alt.datum)
).mark_circle(
stroke='black'
).encode(
longitude='centroid[0]:Q',
latitude='centroid[1]:Q',
size="POP_EST:Q"
)
(basemap + bubbles).project(
type='identity', reflectY=True
)
Choropleths#
An alternative to showing the population sizes as bubbles, is to create a “Choropleth” map. These are geographical heatmaps where the color or each region are mapped to the values of a column in the dataframe.
alt.Chart(gdf_sel).mark_geoshape().encode(
color='POP_EST'
)
When we create choropleth maps, we need to be careful, because although the color changes according to the value of the column we are interested in, the size is tied to the area of each country and we might miss interesting values in small countries just because we can’t easily see them on the map (e.g. if we were to visualize population density).
Lookup datasets#
Sometimes your data is separated in two datasets. One DataFrame with the data and one GeoDataFrame with the geometries.
In this case you can use the lookup transform to collect related information from the other dataset.
You can use the lookup transform in two directions:
Use a
GeoDataFramewith geometries as source and lookup related information in anotherDataFrame.Use a
DataFrameas source and lookup related geometries in aGeoDataFrame.
Depending on your use-case one or the other is more favorable.
First we show an example of the first approach.
Here we lookup the field rate from the df_us_unemp DataFrame, where the gdf_us_counties GeoDataFrame is used as source:
import altair as alt
from altair.datasets import data
gdf_us_counties = data.us_10m(layer="counties")
df_us_unemp = data.unemployment()
alt.Chart(gdf_us_counties).mark_geoshape().transform_lookup(
lookup='id',
from_=alt.LookupData(data=df_us_unemp, key='id', fields=['rate'])
).encode(
alt.Color('rate:Q')
).project(
type='albersUsa'
)
Next, we show an example of the second approach.
Here we lookup the geometries through the fields geometry and type from the gdf_us_counties GeoDataFrame, where the df_us_unemp DataFrame is used as source.
alt.Chart(df_us_unemp).mark_geoshape().transform_lookup(
lookup='id',
from_=alt.LookupData(data=gdf_us_counties, key='id', fields=['geometry', 'type'])
).encode(
alt.Color('rate:Q')
).project(
type='albersUsa'
)