im beggining my journey with gridded data, and ive been trying to plot some temperature data from a netcdf file with cartopy. I followed some examples and i cant understand why my plots have a white line in the middle. (i already checked the data and the matrices are full with numbers, no NaNs)
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatterimport glob
data = xr.open_dataset('aux1.nc')
lat = data.lat
lon = data.lon
time = data.time
Temp = data.air
#Calculo la temperatura media anual
Tanual = Temp.resample(time="y").mean()
#Promedio de todos los meses
Tprom = Temp.mean(dim="time").values
#Grafico
fig = plt.figure(figsize=(10, 4))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.coastlines()
ax.set_global()
ct = ax.contourf(lon,lat,Tprom,transform=ccrs.PlateCarree(),cmap="bwr")
ax.gridlines()
cb = plt.colorbar(ct,orientation="vertical",extendrect='True')
cb.set_label("Temperatura [°C]")
ax.set_xticks(np.arange(-180,181,60), crs=ccrs.PlateCarree())
ax.set_yticks(np.arange(-90,91,30), crs=ccrs.PlateCarree())
lon_formatter = LongitudeFormatter(zero_direction_label=True)
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
Good question! The problem is that for most gridded climate data the longitude coordinate looks something like:
So there's no explicit
longitude=0point, and this often gives you a thin white line in the plot. I see this problem in published papers (even 'Nature') sometimes too!There are many ways to get around this, but the easiest way is to use the
cartopypackage, which has a utility calledadd_cyclic_pointthat basically interpolates the data either side of thelongitude=0point. (Ref: https://scitools.org.uk/cartopy/docs/v0.15/cartopy/util/util.html)The only downside of this method is that when using
xarrayit means you have to extract the data manually and then you lose the metadata, so here's a function I wrote to keep this nice and easy to use, while maintaining metadata.Example
So, for example, if my initial DataArray looks like:
And when I plotting the time-mean, gives this:
Now, I can use my function to generate a new, interpolated DataArray like this:
As you can see, the longitude coordinate has been extended by one point, to go from 144->145 length, this means it now 'wraps around' the
longitude=0point.This new DataArray, when plotted, gives a plot without the white line :)
Hope that helps!! :)