Fill polygon with pattern instead of color Geopandas

4.7k views Asked by At

I'm trying to fill polygons with some pattern instead of a color (due to I must print the project B&W). So far I've only managed to fill them with a grayscale but I would like to take the pattern approach if is there any way to do so.

A piece of my code is the following:

if info['max']=='catarro':
    poly = Polygon(shape, facecolor = "#DDDDDD", alpha = alpha, linewidtt = 0.01)
    plt.gca().add_patch(poly)

This if statement is inside a for loop which runs over info and shape. If some fact of info matches with a string, I just color a poly and add it as a patch over a shapefile.

I also would like to add this pattern in some manner to a legend.

Thanks in advance.

1

There are 1 answers

0
jdmcbr On BEST ANSWER

A recent commit to geopandas allows for passing a hatch argument to the plot method on a GeoDataFrame, so if you installed from the latest source, and you have a GeoDataFrame named gdf, you can do:

gdf.plot(facecolor="#DDDDDD", hatch="//")

You could then plot any subset you want, based on matching some attribute. It is a little unclear to me from your example how your data are structured, but something like:

gdf[gdf["key"] == value1].plot(facecolor="#DDDDDD", hatch="//")
gdf[gdf["key"] == value2].plot(facecolor="#DDDDDD", hatch="o")

and so on.

The most recent geopandas available on pip or conda does not have this functionality. You can still pass the hatch keyword to matplotlib.patches.Polygon (which seems to be what you are using in your example) to control the styling, which would in your example above just be:

 poly = Polygon(shape, facecolor="#DDDDDD", alpha=alpha, linewidth=0.01, hatch="\\")

A fuller demo of plotting hatches is available in the matplotlib gallery.

To add a legend, you can keep a list of plotted polygons, and associated labels, and pass those to legend. So, inside your loop above, something like:

polys.append(poly)
labels.append(search_str)

And then, outside your loop:

ax.legend(polys, labels)