简体   繁体   中英

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

I have created the map of world from inherent datasets of geopandas as follows:

world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

I have plotted the map of world by highlighting the unique continents using

world.plot("continent", legend = True)

The legends are also present in the plot. It looks as follows: 在此处输入图像描述

I get unique color for each continent automatically. However, I'd like to define the color for each continent myself as well as have them in the legends. To define unique color for each continent, I created a dictionary color_dict which looks as follows:

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

And then I appended it as a new column to the world geopandas dataframe and created the plot again.

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

在此处输入图像描述

I get the desired color for each continent. However, now I am not getting the continents name and color in the legend. How can I bring the legends in the plot when I define the color myself?

You may find that you have better results, and greater control, if you convert the geopandas geometries to polygon patches using descartes, and then generate the plots using matplotlib.

Plotting from geopandas can be finicky. it may take some trial and error to get exactly what you want.

Ensure that you have these packages in your module

from matplotlib import pyplot
from descartes import PolygonPatch
from geopandas import GeoDataFrame

PolygonPatch allows you to specify an edge color and face color for each geometry.

With pyplot you should be able to create the legend you desire.

Form your geodataframe (gdf) of the continents. For each continent in your gdf, form a PolygonPatch with the desired face color. Then add the patches to a pyplot figure. With pyplot, you should be able to specify a legend and manipulate it more easily.

Here is some documentation on PolygonPatches, and an example of plotting them (albeit not with the exact legend formatting you are seeking): https://pypi.org/project/descartes/ https://geoffboeing.com/2014/09/visualizing-summer-travels-part-6-projecting-spatial-data-python/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM