cartopy icon indicating copy to clipboard operation
cartopy copied to clipboard

Legends for feature artists

Open poplarShift opened this issue 5 years ago • 2 comments

Fixes #334.

Enables legends for FeatureArtists by implementing a legend handler and registering it with matplotlib.

This necessitated factoring out some of the code in the FeatureArtists' draw method to make it accessible to the new HandlerFeature legend handler.

As for tests, I haven't looked into how to test legend handling in matplotlib. Can do that though if you think this PR is useful!

Example:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature

ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([80, 170, -45, 30])

states_provinces = cfeature.NaturalEarthFeature(
    category='cultural',
    name='admin_1_states_provinces_lines',
    scale='50m',
    facecolor='none')

land = ax.add_feature(cfeature.LAND, facecolor='wheat', edgecolor='black')
prov = ax.add_feature(states_provinces, edgecolor='gray', ls=':')
plt.legend(handles=[land, prov], labels=['Land', 'Province borders'], loc='lower left')

PS: cb3de4f draws all legend artists as Polygons, which looks as below, will also respect facecolor options and is much simpler even for LineStrings but may look non-intuitive when facecolor=none.

image

cb3de4f adds another if/else clause based on facecolor to decide between Rectangle and Line2D for the legend artist, which looks like

image

PPS: I have a vague feeling that the legend artists could have been based off of HandlerPathCollection since that is what the FeatureArtist is drawing but I could not find a way to make the right submethods available to the handler since the actual artist is not based off PathCollection.

poplarShift avatar Mar 29 '20 20:03 poplarShift

I've also submitted the CLA now.

poplarShift avatar Apr 30 '20 13:04 poplarShift

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

CLAassistant avatar Apr 08 '24 16:04 CLAassistant