首页 > 解决方案 > 如何旋转 matplotlib 地图?

问题描述

从我从https://s3.amazonaws.com/nyc-tlc/misc/taxi_zones.zip获得的 shapefile 开始,我想绘制曼哈顿区,并为每个出租车区绘制轮廓。

此代码单独旋转每个单独的滑行区,而不是一次旋转所有。

import geopandas as gpd
from matplotlib import pyplot as plt


fname = "path_to_shapefile.shp"
df = gpd.read_file(fname)
df = df[df['borough'] == "Manhattan"]
glist = gpd.GeoSeries([g for g in df['geometry']])
glist = glist.rotate(90)
glist.plot()

在此处输入图像描述

[编辑] 我进一步完善了它,以便能够以编程方式旋转图像。但是,如果我添加一个图例,那么它也会被旋转,这是不可取的。仍在寻找更好的解决方案。请注意,还有这个 stackoverflow 帖子(如何将 matplotlib 图旋转 90 度?),但是,旋转图而不是图像的解决方案仅适用于 90 度旋转。

import geopandas as gpd
from matplotlib import pyplot as plt

import numpy as np
from scipy import ndimage
from matplotlib import transforms


fname = "path_to_shapefile.shp"
df = gpd.read_file(fname)
df = df[df['borough'] == "Manhattan"]
df.plot()
plt.axis("off")
plt.savefig("test.png")

img = plt.imread('test.png')

rotated_img = ndimage.rotate(img, -65)
plt.imshow(rotated_img, cmap=plt.cm.gray)
plt.axis('off')
plt.show()

[编辑2]

对@PMende 下面给出的答案的简单修改解决了它。

df = gpd.read_file(fname)
df = df[df['borough'] == "Manhattan"]
glist = gpd.GeoSeries([g for g in df['geometry']])
glist = glist.rotate(-65, origin=(0,0))
glist.plot()

关键是围绕一个点旋转所有对象,而不是围绕它们各自的原点旋转。

[编辑 3] 如果有人试图这样做,并且需要将生成的旋转地理序列保存到数据框中(例如,根据附加列为几何图形着色),则需要创建一个新的,只需编写

df['geometry'] = glist

不起作用。我现在不知道为什么。但是,以下代码对我有用。

new_dataframe = gpd.GeoDataFrame(glist)
new_dataframe = new_dataframe.rename(columns={0:'geometry'}).set_geometry('geometry')
new_dataframe.plot()

在此处输入图像描述

标签: pythonmatplotlibgeopandas

解决方案


如果我正确理解 GeoPandas 的文档,您可以指定每个几何图形的旋转原点(默认情况下是每个几何图形的中心)。为了获得您想要的行为,您可以围绕相同的原点旋转每个形状。

例如:

import geopandas as gpd
from matplotlib import pyplot as plt


fname = "path_to_shapefile.shp"
df = gpd.read_file(fname)
df = df[df['borough'] == "Manhattan"]

center = df["geometry"].iloc[0].centroid()
glist = gpd.GeoSeries([g for g in df['geometry']])
glist = glist.rotate(90, origin=center)

glist.plot()

我自己无法对此进行测试,但希望它能让您朝着正确的方向开始。

(尽管我也同意@martinfeleis 的观点,即不一定要旋转几何图形,而是要旋转绘图。)


推荐阅读