Home > other >  How to add hatching by condition with GEOPANDAS and matplotlib
How to add hatching by condition with GEOPANDAS and matplotlib

Time:03-12

I try to plot a map, where a value should define the type of hatching for each polygon. I managed to get a hatch for the total plot, but not based on a condition. Is there a way to do this with geopandas? My code:

import matplotlib as mpl
import matplotlib.pyplot as plt
import geopandas as gpd
from matplotlib.colors import Normalize

project_data = 'XXX'
border = gpd.read_file(f'{project_data}GIS/border.json')
data = gpd.read_file(f'{project_data}GIS/shape.json')

def marker(row, field):
    m = ''
    if (row[field] <= 0):
        m = ''
    elif (row[field] <= 0.5):
        m = '--'
    elif (row[field] <= 1):
        m = '/////'
    elif (row[field] <= 1.6):
        m = 'x'
    return m

data['UI_P45_M'] = data.apply(marker, field='UI_P45', axis=1)

field1 = 'AL_CUR_I'
hatch1 = 'UI_P45_M'
cmap = mpl.cm.get_cmap('pink_r')

fig, ax = plt.subplots(1)
ax.axis('off')
border.plot(facecolor="none", edgecolor="black",
       ax=ax, zorder=2, linewidth=0.5)
data.plot(
column=field1, linewidth=0, norm=Normalize(0, 1.2),
cmap=cmap, ax=ax, hatch=hatch1, zorder=1
)

fig = plt.gcf()

plt.savefig(f'{project_data}results/hatched.pdf')
plt.close(fig)

I also tried to put a layer on top where I do the hatching like this:

border.plot(facecolor="none", edgecolor="black",
           ax=ax,  zorder=3, linewidth=0.5)

data.plot(
    column=field1, linewidth=0,norm=Normalize(0,1.2),
    cmap=cmap, ax=ax, zorder=1
)
data.plot(
    column=field1, linewidth=0, hatch=hatch1,
    facecolor='none',
    ax=ax, zorder=2
)

... but still it doesn't show up. The picture that I get is this:

What am I doing wrong?

CodePudding user response:

Plotting a geodataframe with polygon geometries leverages matplotlib's enter image description here

  • Related