Search code examples
jupyter-notebookcartopy

How to add a physical file path to os.path.join?


I am a beginner in Python and Jupyter noteboook, I am trying to use Cartopy to plot the data I got from NOAA. I got the code as below, and what I am having issues is the "os.path.join" part, as my data set is saved in my portable disc. I tried to use the physical path and add that to the code I found. But it showed me a "KeyError: '/Elements'" The physical path is : "/Elements/Capstone_Project_Data/NOAA/air.mon.amon.nc"

The code is as below: Any suggestion and help would be highly appreciated. Thank you very much!

import os
import matplotlib.pyplot as plt
from netCDF4 import Dataset as netcdf_dataset
import numpy as np

from cartopy import config
import cartopy.crs as ccrs


# get the path of the file. It can be found in the repo data directory.
fname = os.path.join(config["/Elements"],'/Capstone_Project_Data','/NOAA',
                     #'/Elements','/Capstone_Project_Data','/NOAA',
                     'air.mon.amon.nc'
                     )

dataset = netcdf_dataset(fname)
sst = dataset.variables['sst'][0, :, :]
lats = dataset.variables['lat'][:]
lons = dataset.variables['lon'][:]

ax = plt.axes(projection=ccrs.PlateCarree())

plt.contourf(lons, lats, sst, 60,
             transform=ccrs.PlateCarree())

ax.coastlines()

plt.show()


Solution

  • It looks like you are attempting to adapt this example from the Cartopy documentation? https://scitools.org.uk/cartopy/docs/latest/matplotlib/advanced_plotting.html?highlight=config#contour-plots

    In that example Cartopy's config dictionary is used to determine where some standard sample data is located. If you are providing your own data then there is no need to use the config dictionary at all, you can directly specify the path to the file, you maybe don't even need the os.path.join at all:

    # Correct this if your path is different
    fname = "/Elements/Capstone_Project_Data/NOAA/air.mon.mean.nc"
    dataset = netcdf_dataset(fname)
    

    (Note that if you use os.path.join it will insert the / for you so they don't need to prefix every element.)

    The rest of the example will presumably not work because as it is written it is looking for the sst variable in the netcdf file, so you will have to change that to load the variable you are interested in from your file.