Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I get legend when I specify user-defined color for plotting maps using geopandas? #2279

Closed
hbshrestha opened this issue Dec 31, 2021 · 2 comments
Labels

Comments

@hbshrestha
Copy link

hbshrestha commented Dec 31, 2021

I have searched the answer to my question on different websites. This looks like a simple issue, but I could not figure it out.

Question about geopandas

I have created the geopandas dataframe world by reading file from inherent datasets of geopandas. And then I plotted the continents as follows:

world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
world.plot("continent", legend = True)

image

I'd like to provide my own colors to the continents and add them to the legends. I created a dictionary called color_dict and added it as a new column to world.

color_dict = {'Oceania': 'yellow',
 'Africa': 'brown',
 'North America': 'maroon',
 'Asia': 'blue',
 'South America': 'green',
 'Europe': 'red',
 'Seven seas (open ocean)': 'skyblue',
 'Antarctica': 'white'}

world["Colors"] = world["continent"].map(color_dict)

world.plot("continent",
           color = world["Colors"],
           legend = True)

I get the colors for the continents that I set. However, I don't get the continents with colors in the legend. I am not able to figure out why this is the case. I am getting a UserWarning: Only specify one of 'column' or 'color'. Using 'color'.
warnings.warn(
Is there a way that I can get the color I defined for each continent in the map and the name of continent in the legend as well?

image

@martinfleis
Copy link
Member

Hi, this is not entirely supported at the moment (we are aware and plan to change it). At the moment, you have to build the legend by yourself.

color_dict = {'Oceania': 'yellow',
 'Africa': 'brown',
 'North America': 'maroon',
 'Asia': 'blue',
 'South America': 'green',
 'Europe': 'red',
 'Seven seas (open ocean)': 'skyblue',
 'Antarctica': 'white'}

world["Colors"] = world["continent"].map(color_dict)

ax = world.plot(color = world["Colors"])

# add manual legend
from matplotlib.lines import Line2D
custom_points = [Line2D([0], [0], marker="o", linestyle="none", markersize=10, color=color) for color in color_dict.values()]
leg_points = ax.legend(custom_points, color_dict.keys())
ax.add_artist(leg_points)

Screenshot 2022-02-21 at 15 46 09

@hbshrestha
Copy link
Author

Thank you for your response!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants