【问题标题】:Visualize a generic GeoJson file with Plotly使用 Plotly 可视化通用 GeoJson 文件
【发布时间】:2021-08-18 06:23:45
【问题描述】:

我想绘制 GeoJson 文件中包含的一些多边形。是否可以在 Plotly 中可视化未直接链接到真实世界位置的 GeoJson 文件?

例如,我可以使用 GeoPandas 绘制通用 GeoJson 文件:

import json
geodata = json.loads(
"""{ "type": "FeatureCollection",
    "features": [
      { "type": "Feature",
        "geometry": {"type": "Polygon", "coordinates": [[[0,0],[0,1],[1,1]]]},
        "properties": {"id": "upper_left"}
      },
      { "type": "Feature",
        "geometry": {"type": "Polygon", "coordinates": [[[0,0],[1,1],[1,0]]]},
        "properties": {"id": "lower_right"}
      }
    ]
}""")

import geopandas as gpd
df_shapes = gpd.GeoDataFrame.from_features(geodata["features"])
df_shapes.plot(color="none")

结果显示 GeoJson 中包含的两个多边形(三角形):

如何使用 Plotly 绘制相同的地图? This answer 建议使用范围来限制显示的底图。没有底图怎么办?

(我不是在问如何用一条线绘制一个正方形。GeoJson 只是一个简化的例子。)

【问题讨论】:

    标签: python plotly


    【解决方案1】:

    plotly shapes可以画出来。

    使用痕迹

    然后是 list / dict 理解将 geojson 多边形重构为 plotly 结构

    import json
    
    geodata = json.loads(
        """{ "type": "FeatureCollection",
        "features": [
          { "type": "Feature",
            "geometry": {"type": "Polygon", "coordinates": [[[0,0],[0,1],[1,1]]]},
            "properties": {"id": "upper_left"}
          },
          { "type": "Feature",
            "geometry": {"type": "Polygon", "coordinates": [[[0,0],[1,1],[1,0]]]},
            "properties": {"id": "lower_right"}
          }
        ]
    }"""
    )
    
    go.Figure(
        [
            go.Scatter(
                **{
                    "x": [p[0] for p in f["geometry"]["coordinates"][0]],
                    "y": [p[1] for p in f["geometry"]["coordinates"][0]],
                    "fill": "toself",
                    "name": f["properties"]["id"],
                }
            )
            for f in geodata["features"]
        ]
    ).update_layout(height=200, width=200, showlegend=False, margin={"l":0,"r":0,"t":0,"b":0})
    

    使用shapes

    • 使用geopandas几何获取SVG然后提取路径
    • 将这些多边形作为形状添加到布局
    from bs4 import BeautifulSoup
    
    # input to plotly is path.  use shapely geometry svg path for this
    df_shapes = df_shapes.assign(
        svgpath=df_shapes["geometry"].apply(
            lambda p: BeautifulSoup(p.svg()).find("path")["d"]
        )
    )
    
    go.Figure(
        layout=dict(
            height=200,
            width=200,
            showlegend=False,
            margin={"l": 0, "r": 0, "t": 0, "b": 0},
            xaxis={"range": [0, 1]},
            yaxis={"range": [0, 1]},
            shapes=[{"type": "path", "path": p} for p in df_shapes["svgpath"]],
        )
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-28
      • 1970-01-01
      • 2020-08-04
      • 2015-12-11
      • 2021-09-25
      • 1970-01-01
      • 2021-11-11
      • 2021-07-20
      相关资源
      最近更新 更多