Stream: python-questions

Topic: shifting longitudes


view this post on Zulip Christine Shields (May 09 2023 at 20:15):

Hi! Newbie python question: What is the preferred way to shift longitudes (i.e. -180 to +180 to 0- 360, or vice vera) using xarray? Could someone please give me an example? I am plotting a 1d array with longitude on the x-axis, but anticipate needing to do this with lat/lon spatial data as well. Thanks!

view this post on Zulip Brian Medeiros (May 09 2023 at 21:32):

This is how I do it, @Christine Shields :

def lonFlip(data):
    # NOTE: this assumes global values
    tmplon = data['lon']
    tmpdata = data.roll(lon=len(tmplon) // 2, roll_coords=True)
    lonroll = tmpdata['lon'].values
    if tmplon.min() >= 0:
        # flip to -180:180
        tmpdata = tmpdata.assign_coords({'lon': np.where(lonroll >= 180, lonroll - 360, lonroll)})
    else:
        # flip from -180:180 to 0:360
        # tmpdata = tmpdata.assign_coords({'lon': ((lonroll + 360) % 360)})
        tmpdata = tmpdata.assign_coords({'lon': lonroll%360})
    return tmpdata

view this post on Zulip Katie Dagon (May 09 2023 at 21:44):

If you're using cartopy, you can also set the central_longitude. This might not help for analysis but I've found it helpful for shifting the view when plotting. Another thing I have found useful is add_cyclic to help with wrapping global data.

view this post on Zulip Christine Shields (May 09 2023 at 21:52):

Thanks!!!


Last updated: May 16 2025 at 17:14 UTC