Mapping with Geopandas

Mapping is a GIS specialization unto itself, but in this reading I want to provide a really quick intro to some of the tools available for mapping data with geopandas.

plot()

As we saw in our previous readings, the .plot() command is an easy way to create maps in geopandas. Just running .plot() will result in geopandas visualizing our data:

[12]:
import geopandas as gpd

# Load GIS data
world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

# Plot!
world.plot()
[12]:
<AxesSubplot:>
_images/gis_mapping_2_1.png

Moreover, as we saw in our intro reading, if you pass .plot() a column name, geopandas will color each observation based on the value of that variable to create something called a choropleth map:

[2]:
world["gdp_per_cap"] = world["gdp_md_est"] / world["pop_est"]
world = world[world["name"] != "Antarctica"].copy()
world.plot("gdp_per_cap", cmap="Reds")
[2]:
<AxesSubplot:>
_images/gis_mapping_4_1.png

(Note the geopandas .plot() method also accepts all the usual arguments you might pass to matplotlib, like cmap, which controls the colors used in the plot).

And that’s the basics of plotting! If you’d like to know more about the .plot() function, you can read more about it here.

Mapping with Altair

You aren’t limited to the .plot() method (and matplotlib syntax) for plotting though – you can also make Altair maps with the alt.utils.sanitize_dataframe() method:

[15]:
import altair as alt

world = alt.utils.sanitize_dataframe(world)

alt.Chart(world[world["name"] != "Antarctica"]).mark_geoshape().encode(
    color="pop_est", tooltip=["name", "pop_est"]
)

[15]:

Note that altair does not, natively, respect the CRS of the passed geodataframe, but it does have a project() method for re-projecting. You can find a full list of supported projections here. Pictures of all projects available a little down from this link.

[25]:
alt.Chart(world[world["name"] != "Antarctica"]).mark_geoshape().project(
    "equalEarth"
).encode(color="pop_est", tooltip=["name", "pop_est"])

[25]:

Native Interactive Maps

But perhaps the coolest mapping trick that is provided by geopandas is the ability to create interactive maps just using the .explore() method!

[29]:
world.explore()
[29]:
Make this Notebook Trusted to load map: File -> Trust Notebook