Drawing maps with Altair

Now, let's reproduce the map. It is actually pretty straightforward. First, we need to specify the source for the boundaries dataset and the properties of the projection:

url = 'https://unpkg.com/world-atlas@1/world/50m.json'

data_geo = alt.topo_feature(url, feature='countries')
proj = {'center':[10, 52], 'type':'conicEquidistant', 'scale':800}

As you can see, Altair can be linked to the data source and will pull the data from the web during runtime. It is a nice feature, as we can similarly link it to the dataset we'll be constantly updating, hence getting a real-time data snapshot. We'll use that option in Chapter 17, Let's Build a Dashboard, to build a dashboard. Now, we will create another chart object, using projection and the data sourcethis will be our base map:

basemap = alt.Chart(data_geo).mark_geoshape(
clip=True,
fill='lightgray',
stroke='white',

).properties(
width=700,
height=700,
).project(**proj)

Finally, we need to get the points and create another chart object, encoding coordinates, marker size, and the projection:

mask = data[['Latitude', 'Longitude']].notnull().all(1)
points = alt.Chart(data[mask]).mark_circle(clip=True, color='red', opacity=.5).encode(
latitude='Lattitude',
longitude='Longitude',
size=alt.Size('killed total:Q', scale=alt.Scale(type='linear', range=[10, 1000], domain=[10, 1_500_000]), title='Casualties'),
color=alt.value('red'),
tooltip=['name', 'killed total'],
href = 'url'
).project(**proj)

Finally, we need to overlay the two charts into one. In Altair, it is very easyall we need is to add them together (note, however, that, in this case, the order of charts is importantwhichever is last in the operation will be on top of the other). Similarly, the pipe and division symbols put charts on a side or below one another:

map = basemap + points;
map

Here is the resulting map. Note that we have tooltips with the values we defined, and, thanks to the href argument, a Wiki page will be opened on a click for each object:

Unfortunately, due to various reasons, Vega—and, therefore, Altair—does not support pan/zoom for maps, for now. If you need to zoom into your map, the Folium library (a Python wrapper around the famous leaflet.js library) might be a better choice. Folium supports both geopandas dataframes and Altair specifications.

Now, Altair charts can be useful inside your Notebooksbut how to export them as a static image orbetter yeta standalone interactive application?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.162.65