【问题标题】:Plotting Linestrings with a Colomap - Geopandas and Folium用 Colomap 绘制线串 - Geopandas 和 Folium
【发布时间】:2022-01-19 23:29:11
【问题描述】:

我有一个 geopandas 数据框,其中包含约 500 个线串和一个名为 total 的列,其中包含一个介于 0 和 1 之间的数字。

我想用取决于total 值的颜色在folium 地图上绘制线串。因此,我定义了一个颜色图如下:

colormap = cm.LinearColormap(colors=['lightblue','blue'])

我正在使用以下代码绘制所有内容:

m = folium.Map(zoom_start=10, tiles='CartoDB positron')

for _, r in gdf.iterrows():
    geo_j = gpd.GeoSeries(r['geometry']).to_json()
    geo_j = folium.GeoJson(data=geo_j,
                           style_function=lambda x:
                                      {'lineColor':colormap(r['total']),
                                       'color': colormap(r['total']),
                                       'fill':True,
                                       'opacity': 1, 
                                       'fillColor': colormap(r['total'])})
    geo_j.add_to(m)

我尝试了所有线条颜色、颜色、填充颜色、不透明度等的组合,但即使colormap(r['total'] 工作正常(总是检索不同的 rgb),所有线条总是用相同的颜色绘制:

谁能帮忙?

【问题讨论】:

    标签: geopandas folium


    【解决方案1】:
    import requests
    import geopandas as gpd
    import plotly.graph_objects as go
    import itertools
    import numpy as np
    import pandas as pd
    import shapely.geometry
    
    # get geometry of london underground stations
    gdf = gpd.GeoDataFrame.from_features(
        requests.get(
            "https://raw.githubusercontent.com/oobrien/vis/master/tube/data/tfl_stations.json"
        ).json()
    )
    
    # limit to zone 1 and stations that have larger number of lines going through them
    gdf = (
        gdf.loc[gdf["zone"].isin(["1", "2"]) & gdf["lines"].apply(len).gt(2)]
        .reset_index(drop=True)
        .rename(columns={"id": "tfl_id", "name": "id"})
    )
    
    # wanna join all valid combinations of stations...
    combis = np.array(list(itertools.combinations(gdf.index, 2)))
    
    # generate dataframe of all combinations of stations
    gdf_c = (
        gdf.loc[combis[:, 0], ["geometry", "id"]]
        .assign(right=combis[:, 1])
        .merge(
            gdf.loc[:, ["geometry", "id"]],
            left_on="right",
            right_index=True,
            suffixes=("_start_station", "_end_station"),
        )
    )
    
    # generate linestrings between stations
    gdf = gpd.GeoDataFrame(
        geometry=gdf_c.select_dtypes("geometry").apply(shapely.geometry.LineString, axis=1),
        data=gdf_c,
        crs="EPSG:4326",
    )
    gdf["total"] = np.random.uniform(0, 1, len(gdf))
    
    # now use explore that uses folium
    gdf.explore("total", cmap="Blues", tiles="CartoDB positron")
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 2020-09-24
      • 2021-11-03
      • 1970-01-01
      • 2021-04-02
      • 2016-11-10
      • 2020-01-20
      • 2018-10-03
      相关资源
      最近更新 更多