Jojo
Jojo

Reputation: 53

heat map on city plot (Geopandas)

Hey I am trying to plot a heat map where the 'heat' is indicates by the 'count' column of the data frame:

|             geometry        | count |
|-----------------------------|-------|
|   POINT (6.92334 50.91695)  |   10  |
|   POINT (6.91970 50.93167)  |    8  |
|   POINT (6.96946 50.91469)  |    2  |
|   POINT (6.96266 50.94713)  |   72  |
|   POINT (6.93751 50.93832)  |  267  |

I have matched the coordinate system to the base map:

gdg_crs = gdg.to_crs(epsg=3857) 

and tried to plot it with the following code; cx.add_basemap to plot it on the city map (this worked before without putting column='count' and cmap='coolwormth' yielding a map with all the point coordinates as points on the city map):

g_plot = gdg_crs.plot(column='count', cmap='coolwarmth', figsize = (15,15))
plt.ylim(6.606e6, 6.616e6)
plt.xlim(768000,784000)
cx.add_basemap(g_plot)

it worked but the map was only purple and i want to adjust the colours (say which color ranges over which interval) because they range very widely is that possible? Any ideas?

Upvotes: 0

Views: 1785

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31196

  • an alternate is an interactive folium map
  • have experimented with explore() and found I couldn't fully control color and size at same time. Hence used monkey patching to override style_function
import io
import pandas as pd
import geopandas as gpd
import shapely
import folium
import wrapt

df = pd.read_csv(
    io.StringIO(
        """|             geometry        | count |
|   POINT (6.92334 50.91695)  |   10  |
|   POINT (6.91970 50.93167)  |    8  |
|   POINT (6.96946 50.91469)  |    2  |
|   POINT (6.96266 50.94713)  |   72  |
|   POINT (6.93751 50.93832)  |  267  |"""
    ),
    sep="|",
).pipe(
    lambda d: d.drop(columns=[c for c in d.columns if "Unnamed" in c]).rename(
        columns={c: c.strip() for c in d.columns}
    )
)

# wanna intercept geopandas.explore() style function so can set size too
@wrapt.patch_function_wrapper(folium, "GeoJson")
def new_style(wrapped, instance, args, kwargs):
    def style_fn(x):
        return {
            "fillColor": x["properties"]["__folium_color"],
            "color": x["properties"]["__folium_color"],
            "radius": x["properties"]["size"],
            "fillOpacity":.8
        }

    if "_style_column" in str(kwargs["style_function"]):
        kwargs["style_function"] = style_fn
    return wrapped(*args, **kwargs)


gdf = gpd.GeoDataFrame(
    df, geometry=df["geometry"].apply(shapely.wkt.loads), crs="epsg:4326"
)
# normalize sizes...
gdf["size"] = gdf["count"].rank() * 20

gdf.explore(cmap="Reds", column="count")

enter image description here

Upvotes: 0

Related Questions