Reputation: 1
I have created a netCDF file using xarray in python with the code below:
latitude_save = sorted(list(set(copy2_sorted['lat'])))
longitud_save = sorted(list(set(copy2_sorted['lon'])))
time_save = sorted(list(set(copy2_sorted['time'])))
tmp = np.array(copy2_sorted['temp']).reshape(len(time_model), 3, 4)
xrds = xr.Dataset(
coords=dict(time=time_save,
lat=latitude_save,
lon=longitud_save),
data_vars=dict(tas=(['time', 'lat', 'lon'], tmp)))
xrds = xrds.rio.write_crs("EPSG:4326", inplace=True)
file_save = 'C:/Users/72541988B/Desktop/Copernicus/SSP1-1.9/Tas/{}_tas3.nc'.format(model)
my_enocding = {'time': {'dtype': 'int32', '_FillValue': None},
'lat': {'dtype': 'float32', '_FillValue': None},
'lon': {'dtype': 'float32', '_FillValue': None},
'tas': {'dtype': 'float32', '_FillValue': float('nan'), 'zlib': False}
}
xrds.to_netcdf(file_save, encoding=my_enocding)
(print('Se ha guardado: {}'.format(model)))
xrds = xr.open_dataset("C:/Users/72541988B/Desktop/Copernicus/SSP1-1.9/Tas/CAMS_CSM_tas7.nc")
I have made sure that the latitude and longitude of the code are well saved, by later oppening the nc file in python again and watching the latitude and longitude values using this:
print(xrds["lat"].values)
Result:
41.1265, 41.9565, 42.8
print(xrds["lon"].values)
Result:
-3.8875, -2.162 , -0.437 , 1.2875
I get defined latitudes and longitudes without any problems. But then when I try to open it in QGIS, the coordinates are not well loaded, in fact it's as if didi not have any coordinate since it creates a grid that extends from 0.0 to 4.0 and from 0.0 to -3.0.
I have used this code to create a netCDF of precipitation and I had not problems, but when I do the same with the temperature I get this problem when trying to open it in QGIS (because in python everything is okay) so I figure it has something to do with QGIS but I can not tell what. Can anybody help me?
I have tried changing the coordinates of the nc directly in QGIS but it gives me an error because the coordinates are not defined.
I have also tried to define while saving the netCDF file defining the coordinate system EPSG: 4326. But I have the same problem, in python the lecture is okay but in QGIS no.
I have also used rioxarray to define the EPSG coordinates in case there is something wrong with xarray.
Upvotes: 0
Views: 24
Reputation: 609
You should have three steps :
xrds.rio.set_spatial_dims(x_dim='lon', y_dim='lat', inplace=True)
xrds.rio.write_grid_mapping(inplace=True)
xrds.rio.write_crs(crs, inplace=True)
This way, QGIS will understand the attached CRS.
Upvotes: 0