Home > database >  How to make a legend with matplotlib plotting a map?
How to make a legend with matplotlib plotting a map?

Time:01-06

I have the following plot:

enter image description here

Inside this map you see some random coloured areas with numbers in it. The numbers are 12,25,34,38 and 43. Now I want to add a legend in the above left corner with the numbers followed by the name of the area. Something like this:

enter image description here

The annotation (The numbers in the areas) are added though a for loop using the following command ax.annotate(number, xy = ...). Can somebody tell me how to add a legend with all the numbers and text in some sort of a legend similar to the image above?

The numbers and names are both inside a pandas dataframe.

fig, ax = plt.subplots(1,1)
fig.set_size_inches(8,8)                      # setting the size

# Plot values - with grey layout

grey_plot = schap.plot(ax = ax, color = 'grey')
schap.plot(ax = grey_plot, column= col1, cmap= 'YlGnBu', legend = True)

    
# Add annotation for every waterschap with a deelstroomgebied
bbox_props = dict(boxstyle="round", fc="w", ec="gray", alpha=0.9,lw=0.4)
for idx, row in schap.iterrows():    
    if not np.isnan(row[col1]):
        string = str(idx)
        ax.annotate(string, xy=row['coords'], color='black',
                     horizontalalignment='center', bbox=bbox_props, fontsize=7)
        

'schap' is the pandas dataframe with all needed data. schap['text'] contains all names. In a for loop this would be row['text'].

CodePudding user response:

After the loop you can simply add text, for example:

ax.text(0.01, 0.99, legend,
    horizontalalignment='left',
    verticalalignment='top',
    transform=ax.transAxes,
    fontsize=8)

where legend can be updated inside your loop (desc is column with description):

legend = ''
#...

#inside your loop
    legend = legend   f"{idx} {row['text'])}\n"

EDIT: Example with different data (and aligment of legend):

import geopandas
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1,1)
fig.set_size_inches(20,8) 

world.plot(column='gdp_md_est', ax=ax, legend=True)
world['coords'] = world['geometry'].apply(lambda x: x.representative_point().coords[:][0])

bbox_props = dict(boxstyle="round", fc="w", ec="gray", alpha=0.9,lw=0.4)
legend = ''

for idx, row in world.iterrows():
    if row['pop_est'] > 100_000_000:
        plt.annotate(str(idx), xy=row['coords'], color='black',
            horizontalalignment='center', bbox=bbox_props, fontsize=7)
        legend = legend   f"{idx} {row['name']}\n"
        
ax.text(0.01, 0.5, legend,
    horizontalalignment='left',
    verticalalignment='center',
    transform=ax.transAxes,
    fontsize=8);

World map

  •  Tags:  
  • Related