Geopandas Plotting & Legends Symbology - QUESTION
See original GitHub issueIssue Description
Hi All.
I have a question about how plots and legends work with geopandas. I set the colors and line symbology using a list. And i used .plot()
to plot the data
Here is a plot that i made of roads using the cropped natural earth data:
# plotting using geopandas
road_colors = ['black', 'grey', 'grey', 'black', 'grey', 'grey' ]
line_widths = [1, .5, .5, 1, .5,.5]
# plot the data
fig, ax = plt.subplots(figsize = (12, 8))
country_boundary_us.plot(alpha = 1, color="white",
edgecolor = "black",
ax = ax)
us_roads_only.plot(ax=ax, column='type',
cmap = ListedColormap(road_colors),
linewidth = line_widths,
legend = True)
ax.set_axis_off()
plt.axis('equal');
Notice that my legend shows the road symbols as circles. Yet i’d prefer lines.
Here – i try to create a nicer legend using ax.legend()
.
# make it a bit nicer using a dictionary to assign colors and line widths
road_attrs = {'Beltway': ['black',2],
'Secondary Highway': ['grey',.5],
'Road': ['grey',.5],
'Bypass': ['grey', .5],
'Ferry Route': ['grey', .5],
'Major Highway': ['black', 1]}
# plot the data
fig, ax = plt.subplots(figsize = (12, 8))
for ctype, data in us_roads_only.groupby('type'):
data.plot(color=road_attrs[ctype][0],
label = ctype,
ax = ax,
linewidth=road_attrs[ctype][1])
country_boundary_us.plot(alpha = 1, color="white", edgecolor = "black", ax = ax)
ax.legend(title="legend")
ax.set_title("United States Roads by Type", fontsize=25)
ax.set_axis_off()
plt.axis('equal');
I may be missing something. But can geopandas create a legend using the unique symbology applied to each (group) like ax.legend()
can do natively if there is a label object? Or can you kindly help me understand how i would customize a legend created by geopandas? Perhaps my approach is wrong.
My GOAL: i’m trying to figure out the best way to teach students how to create a map with a legend in python.
Many thanks for any guidance.
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (5 by maintainers)
HAHAHA got it @martinfleis 😃 with COVID and the cold evenings on the horizon perhaps i will find some time to have a look at plotting.py 😃 it’s been on my mind for a while. Thank you!
thanks @jdmcbr ok that makes sense. I had a look at the code and suspected that was the case but i wasn’t fully certain. it would be a very nice feature to have. The matplotlib legend functionality is actually quite nice so it does seem as if geopandas could take advantage of that potentially. I appreciate your response!