question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Polygon handles not passing to legend

See original GitHub issue

I am trying to plot some polygons and lines from geopandas dataframe and add a legend. However, when plotting the polygons, the labels don’t get passed to the legend handles.

So for example

    fig,ax=plt.subplots()
    lineshp.plot(ax=ax,color='k', linewidth=3,label='line')
    polyshp.plot(ax=ax,color='r',label='poly')
    ax.get_legend_handles_labels()

It returns: ([<matplotlib.collections.LineCollection at 0x116681d0>], [‘line’]) and does not include the polygon handles.

Anyone has an idea of how I could fix this? This seems to be a new issue for me.

Issue Analytics

  • State:open
  • Created 6 years ago
  • Reactions:5
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

7reactions
skytruinecommented, Sep 7, 2020

I’m using geopandas 0.8.1, and I also faced this problem. Here is my solution

# load China polygon
    rgn = gpd.read_file(
        'https://geo.datav.aliyun.com/areas_v2/bound/100000_full.json')
    # Administrative divisions at provincial level in China (polygon)
    china = rgn[rgn.level.isna() == False]
    # South China Sea Nine-dash line (polygon)
    nine_lines = rgn[rgn.level.isna()]

    # Drawing features
    fig, ax = plt.subplots(figsize=(8, 8))
    ax = china.plot(ax=ax,
                    facecolor='grey',
                    edgecolor='white',
                    linestyle='--',
                    alpha=0.8,
                    label='Administrative divisions')
    ax = nine_lines.plot(ax=ax,
                         edgecolor='grey',
                         linewidth=3,
                         alpha=0.4,
                         label='South China Sea Nine-dash line')

    # Error in normal writing: No handles with labels found to put in legend.
    # ax.legend(title='Legend', loc='lower left', ncol=1, shadow=True)

    # Alternative solution for "Polygon handles not passing to legend"
    import matplotlib.patches as mpatches
    import matplotlib.pyplot as plt
    pmark = mpatches.Patch(facecolor='grey',
                           edgecolor='white',
                           linestyle='--',
                           alpha=0.8,
                           label='Administrative divisions')
    lmark = mlines.Line2D(
        [],
        [],
        color='grey',
        linewidth=3,
        alpha=0.4,
        label='South China Sea Nine-dash line')
    handles, _ = ax.get_legend_handles_labels()
    ax.legend(
        handles=[
            *handles,
            lmark,
            pmark],
        title="Legend",
        loc='lower left',
        ncol=1,
        shadow=True)
    
    # show figure
    plt.rcParams['legend.title_fontsize'] = 10
    plt.show()

Solution

Although this approach can fulfill my requirements, it’s really cumbersome, and I really hope that geopandas can fix it.

2reactions
jorisvandenbosschecommented, Feb 2, 2018

OK, this is a ‘limitation’ of matplotlib. They only support automatically creating legend handlers for some collections, so for points and lines they do, but not for PatchCollections (polygons). So we could in principle, if a label is passed, create ourselves a legend handle, and pass that to matplotlib.

See https://matplotlib.org/2.0.0/users/legend_guide.html

Read more comments on GitHub >

github_iconTop Results From Across the Web

python - Error `No handles with labels` when trying to relocate ...
(I am plotting a GeoDataFrame.) No handles with labels found to put in legend. (I suspect if it has something to do with...
Read more >
Legends in python | Andrew Wheeler
You can think of handles as just points/lines/polygons that refer to individual parts of the legend. And so combining the lines and polygons...
Read more >
Adding custom names to a GeoPandas legend
The legend comes up empty and I get a message that No handles with labels found to put in legend .
Read more >
matplotlib.pyplot.legend — Matplotlib 3.6.2 documentation
legend () legend(handles, labels) legend(handles=handles) legend(labels) ... be added to the legend are automatically determined, when you do not pass in any ...
Read more >
Customize Map Legends and Colors in Python using Matplotlib
It looks like you have some missing values in your road types. You want to plot all road types even those that are...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found