Search code examples
data-visualizationgisvegavega-litealtair

Vega-Lite / Altair: How to Center or Crop a Map of Europe?


I have some data on European countries. I'm trying to create a visualization in Altair / Vega-Lite using the world-110m data. Everything technically works fine, except that coded boundaries of the countries also include far-away territories, producing a terrible map that looks like this:

Bad Europe Map

Here is my code:

countries = alt.topo_feature(data.world_110m.url, 'countries')
source = df.copy()

map = alt.Chart(countries).mark_geoshape(
    stroke='black'
    ).encode(
    color=alt.Color('SomeStat:Q', sort="descending", scale=alt.Scale(
        scheme='inferno', domain=(min_value,max_value)), legend=alt.Legend(title="", tickCount=6))
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(source, 'CountryId', ['SomeStat', 'CountryName'])
).project(
    type='mercator'
)

Is there a way to crop this map or center it so that I'm only getting Europe and not far-flung territories all over the world?

Alternatively, is there a better public dataset I should be using that only includes Europe?


Solution

  • I don't have your df dataset, so I post rather simple example.

    import altair as alt
    from vega_datasets import data
    
    countries = alt.topo_feature(data.world_110m.url, 'countries')
    
    alt.Chart(countries).mark_geoshape(
        fill='#666666',
        stroke='white'
    ).project(
        type= 'mercator',
        scale= 350,                          # Magnify
        center= [20,50],                     # [lon, lat]
        clipExtent= [[0, 0], [400, 300]],    # [[left, top], [right, bottom]]
    ).properties(
        title='Europe (Mercator)',
        width=400, height=300
    )
    

    enter image description here

    You can control the map view by scale and center, along with its actual plot size (width and height).

    • scale: magnifying parameter
    • center: center point of the view

    If you need to further crop any part of the map, clipExtent can be useful. Please be careful - this array represents the pixel size, not geographical coordinates. (In the above example I have set it [[0, 0], [400, 300]] so it keeps the entire 400x300 px view.