Is it possible to shift a geopandas world map on the x axis (longitude)?

Viewed 527

I'm wondering if there is a way to center a geopandas world map on a particular point of longitude. Basically, just wanting to shift it by about ~5-10 degrees or so.

A previous question was posted several months ago, but didn't receive an answer. Wondering if anyone knows the solution. (Link to the original question on stackoverflow is here)

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
fig, ax = plt.subplots()
world.plot(ax=ax, color=(0.8,0.5,0.5))

Would really appreciate it if someone could help.

Thanks in advance

1 Answers

I found out how to do it:

from shapely.geometry import LineString
from shapely.ops import split
from shapely.affinity import translate
import geopandas

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))

def shift_map(shift):
    shift -= 180
    moved_map = []
    splitted_map = []
    border = LineString([(shift,90),(shift,-90)])
    for row in world["geometry"]:
        splitted_map.append(split(row, border))
    for element in splitted_map:
        items = list(element)
        for item in items:
            minx, miny, maxx, maxy = item.bounds
            if minx >= shift:
                moved_map.append(translate(item, xoff=-180-shift))
            else:
                moved_map.append(translate(item, xoff=180-shift))
    gdf = geopandas.GeoDataFrame({"geometry":moved_map})
    fig, ax = plt.subplots()
    gdf.plot(ax=ax)
    plt.show()
   

In the first step, you create your world and split it on a pre defined border of yours. Then you get the bounds of all elements and check if the bounds match your desired shift. Afterwards you translate every element bigger than your border to the left side of the map and move all other elements to the right side, so that they aling with +180°.

This gives you for example: Shifted map by 120°

A map shifted by 120°

Related