【问题标题】:Matplotlib cannot plot points on basemap from CSV, but plots corectly from JSONMatplotlib 无法从 CSV 在底图上绘制点,但可以从 JSON 中正确绘制
【发布时间】:2020-10-11 06:11:00
【问题描述】:

问题

我正在尝试在底图上绘制一组点。下面是我的代码。但是,它没有正确显示它应该在地图上显示的位置。我在 Dropbox 链接下方添加了我正在使用的 csv 文件。

Dropbox link to the csv file

import pandas as pd
import geopandas
import matplotlib.pyplot as plt
%matplotlib inline

#read data from CSV 
building = pd.read_csv('masteronlyfive.csv')

# convert coords to float type
building = building.astype({"lat": float, "long": float})

# convert to geodata series
building = geopandas.GeoDataFrame(towers, geometry=geopandas.points_from_xy(building.lat,building.long))

# set CRS
building.crs = {'init' :'epsg:4326'}
building.head()

# read basemap file and set CRS
world = geopandas.read_file("South_Africa_Polygon.shp")
world.crs = {'init' :'epsg:4326'}

# Plot basemap
ax = world.plot(color='white', edgecolor='black')

# plot points
building.plot(ax=ax, color='red')

plt.show()

我的尝试

我已获取坐标并将它们重新编码为 json 格式,而不是 csv,因此我从 json 数组读取数据而不是执行 csv 导入,如下所示,它们工作得很好,它对我来说完全令人震惊。

import pandas as pd
import geopandas
import matplotlib.pyplot as plt
%matplotlib inline

#reading from json array
df = pd.DataFrame(
    {'Country': ['building', 'building', 'building', 'building', 'building'],
     'Latitude': [-28.506806, -27.463611, -29.192053, -28.871950, -27.242444],
     'Longitude': [28.613972, 28.040001, 26.235583,27.873739, 28.838861]})

#creating geopandas points from the coordinates
gdf = geopandas.GeoDataFrame(
    df, geometry=geopandas.points_from_xy(df.Longitude, df.Latitude))


#reading the basemap file
world = geopandas.read_file("South_Africa_Polygon.shp")

# plotting the basemap 
ax = world.plot(color='white', edgecolor='black')

# plotting the geodata points
gdf.plot(ax=ax, color='red')

plt.show()

如果完全相同的坐标在 JSON 中可以正常工作,但在 CSV 中不能正常工作,我可能做错了什么。

【问题讨论】:

    标签: python pandas matplotlib geopandas


    【解决方案1】:

    当您创建地理数据框时,更改长/纬度顺序,如下所示:

    # convert to geodata series
    building = geopandas.GeoDataFrame(
        geometry=geopandas.points_from_xy(building.long, building.lat)
    )
    

    您的经度是 x,而不是 y。你的纬度是 y。因此,在处理points_from_xy() 函数时,经度(即x)是第一位的。这是一个非常常见的错误,您可以在图中发现它 - 多边形边界与您的点簇对角线相对,因此通常是纬度/经度的顺序!

    附:我不确定为什么您的原始代码在该代码 sn-p 中引用了 towers 变量,所以我将其删除。

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 2019-06-26
      • 2018-03-05
      • 1970-01-01
      相关资源
      最近更新 更多