在Geopandas和Altair中解决翻转图和投影问题

1 投票
2 回答
44 浏览
提问于 2025-04-14 15:26

我正在尝试使用一些来自ONS的数据来绘制伦敦的多层地图。

import geopandas as gpd
from shapely import wkt

# Convert the 'geometry' column to shapely geometry objects
london_wards_shp['geometry'] = london_wards_shp['geometry'].apply(wkt.loads)
london_wards_gpd = gpd.GeoDataFrame(london_wards_shp, geometry='geometry')
london_wards_gpd = london_wards_gpd.set_crs(epsg=4326)
london_wards_gpd.plot()

但是出现了一个错误:

ValueError: aspect must be finite and positive 

我找到了绘图的解决方案:

london_wards_gpd.plot(aspect=1)

在这里输入图片描述

但接着我想用altair来叠加多个图层,其中一个是整个图层的地图。

> london_wards_map = alt.Chart(london_wards_gpd).mark_geoshape(
>     fill=None,  # No fill
>     stroke='darkgray',  # Black stroke
>     strokeWidth=1  # Stroke width ).encode(
>     tooltip='NAME:N'  # Replace 'NAME' with the actual name of the column that contains the ward names ).properties(
>     width=800,
>     height=600 ).project(
>     type='identity' )
> 
> hackney_wards = london_wards_gpd[london_wards_gpd['DISTRICT']
> =='Hackney']
> #hackney_wards = gpd.GeoDataFrame(hackney_wards, geometry='geometry')  # Convert DataFrame to GeoDataFrame
> #hackney_wards = hackney_wards.set_crs(epsg=4326) hackney_layer = alt.Chart(hackney_wards).mark_geoshape(
>     fill='lightgray',  # No fill
>     stroke='darkgray',  # Black stroke
>     strokeWidth=1  # Stroke width ).encode(
>     tooltip='NAME:N'  # Replace 'NAME' with the actual name of the column that contains the ward names ).properties(
>     width=800,
>     height=600 ).project(
>     type='identity' )

london_wards_map + hackney_layer

在这里输入图片描述

那么为什么它是倒过来的呢?

我不太确定如何诊断这个投影问题。

2 个回答

0

我找到了第一个问题的答案。翻转数据框可以这样做:

定义一个函数来翻转y坐标

def flip_geom(geom):
    geom_type = geom.geom_type
    if geom_type == 'Polygon':
        geom = transform(lambda x, y, z=None: (x, -y), geom)
    elif geom_type == 'MultiPolygon':
        geom = transform(lambda x, y, z=None: (x, -y), geom)
    else:
        raise ValueError('Unhandled geometry type: ' + repr(geom_type))
    return geom
2

请查看文档,了解如何在笛卡尔坐标系中绘图:https://altair-viz.github.io/user_guide/marks/geoshape.html#cartesian-coordinates

alt.Chart(gdf).mark_geoshape().project(
    type='identity',
    reflectY=True
)

输入的几何形状没有经过投影,而是直接使用原始坐标进行绘制,采用的是identity这种投影类型。你还需要定义reflectY,因为在Canvas和SVG中,正的y方向是向下的。

撰写回答