0

I am having trouble adding a basemap to my map. My geodataframe is created using X and Y coords of a bunch of points.

gdf = geo.GeoDataFrame(
df, geometry=gpd.points_from_xy(df['X'], df['Y']))

gdf.set_crs(epsg=3857)

Which look like this: enter image description here

After using contexily to get a basemap, I cannot get the basemap to properly show up. The coords should be showing the bottom of the Mississippi River Basin.

ax = gdf.plot(color="red", figsize=(9, 9))
cx.add_basemap(ax, zoom=0, crs= gdf.crs)

enter image description here

Let me know if there is anything wrong with my code as to why it is not showing up.

Thanks!

2 Answers2

0

It looks like your data is in WGS84/EPSG:4326 (i.e. lat/lon) coordinates. So I think you're confusing geopandas.GeoDataFrame.set_crs, which tells geopandas what the CRS of the data is, with geopandas.GeoDataFrame.to_crs, which transforms the data from the current CRS to the new one you specify. Also note that neither of these operations are in-place by default. So I think you want:

gdf = geo.GeoDataFrame(
    df, geometry=gpd.points_from_xy(df['X'], df['Y'])
)

gdf = gdf.set_crs("epsg:4326")

gdf_mercator = gdf.to_crs("epsg:3857")
Michael Delgado
  • 13,789
  • 3
  • 29
  • 54
0

This really is same as @Michael Delgado answer. It's simpler to state the CRS at GeoDataFrame construction time. Also make sure you are using correct CRS

MWE

import geopandas as gpd
import geopandas as geo
import pandas as pd
import contextily as cx

# construct a dataframe with X and Y of some points in US
places = gpd.read_file(
    gpd.datasets.get_path("naturalearth_cities"),
    mask=gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")).loc[
        lambda d: d["iso_a3"].eq("USA")
    ],
)
df = pd.DataFrame({"X": places.geometry.x, "Y": places.geometry.y})

# user code, state CRS at construction time
gdf = geo.GeoDataFrame(
    df, geometry=gpd.points_from_xy(df["X"], df["Y"]), crs="epsg:4326"
)
ax = gdf.plot(color="red", figsize=(9, 9))
cx.add_basemap(ax, zoom=0, crs=gdf.crs)
Rob Raymond
  • 29,118
  • 3
  • 14
  • 30