-1

How can I plot on a map the data from the variable "r" (relative humidity) of a NetCDF file with cartopy?

from netCDF4 import Dataset
import cartopy.crs as ccrs
import numpy as np
import xarray as xr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
ds = Dataset('relative_humidityEne_Dic2003_2020CMAS.nc', 'r')
lon = ds.variables["longitude"]
lat = ds.variables["latitude"]
level = ds.variables["level"]
time = ds.variables["time"]
r = ds.variables["r"]
ax = plt.axes(projection=ccrs.PlateCarree())
r_ds = ds.variables['r'][0, :, :, :]
plt.contourf(lon, lat, r_ds, transform=ccrs.PlateCarree())
ax.coastlines()
plt.show()

root group (NETCDF3_64BIT_OFFSET data model, file format NETCDF3):
    Conventions: CF-1.6
    history: 2021-02-19 10:03:12 GMT by grib_to_netcdf-2.16.0: /opt/ecmwf/eccodes/bin/grib_to_netcdf -S param -o /cache/data7/adaptor.marsdev.internal-1613728991.1847723-6796-17-440f19fd-bb8f-478f-bc36-959e3e9d9c42.nc /cache/tmp/440f19fd-bb8f-478f-bc36-959e3e9d9c42-adaptor.marsdev.internal-1613728966.210842-6796-20-tmp.grib
    dimensions(sizes): longitude(480), latitude(241), level(8), time(53)
    variables(dimensions): float32 longitude(longitude), float32 latitude(latitude), int32 level(level), int32 time(time), int16 r(time,level,latitude,longitude)
    groups: 
dict_keys(['longitude', 'latitude', 'level', 'time', 'r'])
las dimenciones variable r es:  ('time', 'level', 'latitude', 'longitude')
(53, 8, 241, 480)

----------------------------------------------------------------------
<class 'netCDF4._netCDF4.Variable'>
int16 r(time, level, latitude, longitude)
    scale_factor: 0.001964639476266317
    add_offset: 64.43876426873042
    _FillValue: -32767
    missing_value: -32767
    units: %
    long_name: Relative humidity
    standard_name: relative_humidity
unlimited dimensions: 
current shape = (53, 8, 241, 480)
filling on
las dimenciones variable r es:  ('time', 'level', 'latitude', 'longitude')
(53, 8, 241, 480)

error message:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 3331, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-403ea023eab8>", line 1, in <module>
    runfile('/home/leo/Documentos/Universidad/Trabajo_de_investigación/PerfilesVerticalesContaminantesAtmosfera/Datos/readNetdcf42003_2020CMAS.py', wdir='/home/leo/Documentos/Universidad/Trabajo_de_investigación/PerfilesVerticalesContaminantesAtmosfera/Datos')
  File "/snap/pycharm-professional/230/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "/snap/pycharm-professional/230/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/leo/Documentos/Universidad/Trabajo_de_investigación/PerfilesVerticalesContaminantesAtmosfera/Datos/readNetdcf42003_2020CMAS.py", line 65, in <module>
    plt.contourf(lon, lat, r_ds, transform=ccrs.PlateCarree())
  File "/home/leo/.local/lib/python3.8/site-packages/matplotlib/pyplot.py", line 2577, in contourf
    __ret = gca().contourf(
  File "/home/leo/.local/lib/python3.8/site-packages/cartopy/mpl/geoaxes.py", line 321, in wrapper
    return func(self, *args, **kwargs)
  File "/home/leo/.local/lib/python3.8/site-packages/cartopy/mpl/geoaxes.py", line 1586, in contourf
    result = matplotlib.axes.Axes.contourf(self, *args, **kwargs)
  File "/home/leo/.local/lib/python3.8/site-packages/matplotlib/__init__.py", line 1447, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "/home/leo/.local/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 6335, in contourf
    contours = mcontour.QuadContourSet(self, *args, **kwargs)
  File "/home/leo/.local/lib/python3.8/site-packages/matplotlib/contour.py", line 816, in __init__
    kwargs = self._process_args(*args, **kwargs)
  File "/home/leo/.local/lib/python3.8/site-packages/matplotlib/contour.py", line 1430, in _process_args
    x, y, z = self._contour_args(args, kwargs)
  File "/home/leo/.local/lib/python3.8/site-packages/matplotlib/contour.py", line 1488, in _contour_args
    x, y, z = self._check_xyz(args[:3], kwargs)
  File "/home/leo/.local/lib/python3.8/site-packages/matplotlib/contour.py", line 1514, in _check_xyz
    x = np.asarray(x, dtype=np.float64)
  File "/usr/local/lib/python3.8/dist-packages/numpy/core/_asarray.py", line 102, in asarray
    return array(a, dtype, copy=False, order=order)
TypeError: __array__() takes no arguments (1 given)
desertnaut
  • 57,590
  • 26
  • 140
  • 166
leojim19
  • 29
  • 4
  • Could you please fix your code highlighting? Use three backticks(```) on the line before the code and three at the very end. – hrokr Feb 26 '21 at 07:07

1 Answers1

1

You should be able to do this using my ncplot package (https://pypi.org/project/ncplot/):

from ncplot import view
view('relative_humidityEne_Dic2003_2020CMAS.nc', 'r')

This will create an interactive plot.

Robert Wilson
  • 3,192
  • 11
  • 19
  • when I use (ncplot) I have several errors. File "/usr/local/lib/python3.8/dist-packages/hvplot/converter.py", line 1067, in __call__ raise ImportError('Datashading is not available') ImportError: Datashading is not available – leojim19 Feb 26 '21 at 11:49
  • OK, that is strange. One of the dependencies should install datashader, but it no longer seems to on pypi. But it does on conda-forge. So a recent update to a dependency ust have broken things. I'll update the pypi versions this afternoon. For now you should be able to fix this using `pip install datashader` – Robert Wilson Feb 26 '21 at 13:06
  • File "/usr/local/lib/python3.8/dist-packages/holoviews/plotting/bokeh/element.py", line 1359, in _init_glyphs self._update_glyph(renderer, properties, mapping, glyph, source, source.data) File "/usr/local/lib/python3.8/dist-packages/holoviews/core/options.py", line 227, in __exit__ raise AbbreviatedException(etype, value, traceback) holoviews.core.options.AbbreviatedException: AttributeError: 'str' object has no attribute 'dataspecs' To view the original traceback, catch this exception and call print_traceback() method. – leojim19 Feb 26 '21 at 13:56
  • Would you like to help me with the code I am writing? this line of code gives me an error. ``plt.pcolormesh (ilon, ilat, r_ds, 60, transform = ccrs.PlateCarree ())`` ----------------------------------------------------- # plotear variables en el map ```r_ds = [ds.variables['r'][:]] lon_ds = [ds.variables['longitude'][:]] lat_ds = [ds.variables['latitude'][:]] ilon, ilat = np.meshgrid(lon_ds, lat_ds) h = plt.pcolormesh(ilon, ilat, r_ds, 60, transform=ccrs.PlateCarree()) ax.coastlines() plt.show()``` – leojim19 Feb 26 '21 at 14:17
  • OK. This seems to be an issue with a dependency breaking things. Can you revise your original question so that it is clear which line is causing the problem? Try to remove any code that is irrelevant to the error. For example, printing serves no real purpose here – Robert Wilson Feb 26 '21 at 14:23
  • in my original question I removed the print and added the outputs of ("ds") and the variable ("r"). – leojim19 Feb 26 '21 at 14:52
  • I'll have a look. I've quickly updated the pypi version of ncplot, so that it pins the depencencies. Should work now – Robert Wilson Feb 26 '21 at 18:02
  • Thank you very much, now I can view the maps with the updates to the ncplot library. – leojim19 Feb 27 '21 at 18:51
  • File "/usr/local/lib/python3.8/dist-packages/geoviews/plotting/bokeh/plot.py", line 88, in _update_ranges super(GeoPlot, self)._update_ranges(element, ranges) File "/home/leo/.local/lib/python3.8/site-packages/holoviews/plotting/bokeh/element.py", line 835, in _update_ranges frame_aspect = plot.frame_height/plot.frame_width TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType' – leojim19 Feb 27 '21 at 19:17
  • maps are made. but I would like to show you these messages. – leojim19 Feb 27 '21 at 19:17
  • thanks. Some of the dependencies do not function properly with each other, depending on version installed. I need to resolve this properly – Robert Wilson Mar 01 '21 at 15:07