You can run this notebook in a live session or view it on Github.

# Visualization Gallery

This notebook shows common visualization issues encountered in xarray.

    [1]:

    import cartopy.crs as ccrs
    import matplotlib.pyplot as plt
    import xarray as xr

    %matplotlib inline

Load example dataset:

    [2]:

    ds = xr.tutorial.load_dataset("air_temperature")

    ---------------------------------------------------------------------------
    PermissionError                           Traceback (most recent call last)
    File /usr/lib/python3/dist-packages/pooch/utils.py:262, in make_local_storage(path, env)
        258 if action == "create":
        259     # When running in parallel, it's possible that multiple jobs will
        260     # try to create the path at the same time. Use exist_ok to avoid
        261     # raising an error.
    --> 262     os.makedirs(path, exist_ok=True)
        263 else:

    File /usr/lib/python3.13/os.py:217, in makedirs(name, mode, exist_ok)
        216 try:
    --> 217     makedirs(head, exist_ok=exist_ok)
        218 except FileExistsError:
        219     # Defeats race condition when another thread created the path

    File /usr/lib/python3.13/os.py:217, in makedirs(name, mode, exist_ok)
        216 try:
    --> 217     makedirs(head, exist_ok=exist_ok)
        218 except FileExistsError:
        219     # Defeats race condition when another thread created the path

    File /usr/lib/python3.13/os.py:227, in makedirs(name, mode, exist_ok)
        226 try:
    --> 227     mkdir(name, mode)
        228 except OSError:
        229     # Cannot rely on checking for EEXIST, since the operating system
        230     # could give priority to other errors like EACCES or EROFS

    PermissionError: [Errno 13] Permission denied: '/sbuild-nonexistent'

    The above exception was the direct cause of the following exception:

    PermissionError                           Traceback (most recent call last)
    Cell In[2], line 1
    ----> 1 ds = xr.tutorial.load_dataset("air_temperature")

    File /usr/lib/python3/dist-packages/xarray/tutorial.py:213, in load_dataset(*args, **kwargs)
        176 def load_dataset(*args, **kwargs) -> Dataset:
        177     """
        178     Open, load into memory, and close a dataset from the online repository
        179     (requires internet).
       (...)
        211     load_dataset
        212     """
    --> 213     with open_dataset(*args, **kwargs) as ds:
        214         return ds.load()

    File /usr/lib/python3/dist-packages/xarray/tutorial.py:165, in open_dataset(name, cache, cache_dir, engine, **kws)
        162 downloader = pooch.HTTPDownloader(headers=headers)
        164 # retrieve the file
    --> 165 filepath = pooch.retrieve(
        166     url=url, known_hash=None, path=cache_dir, downloader=downloader
        167 )
        168 ds = _open_dataset(filepath, engine=engine, **kws)
        169 if not cache:

    File /usr/lib/python3/dist-packages/pooch/core.py:227, in retrieve(url, known_hash, fname, path, processor, downloader, progressbar)
        222 action, verb = download_action(full_path, known_hash)
        224 if action in ("download", "update"):
        225     # We need to write data, so create the local data directory if it
        226     # doesn't already exist.
    --> 227     make_local_storage(path)
        229     get_logger().info(
        230         "%s data from '%s' to file '%s'.",
        231         verb,
        232         url,
        233         str(full_path),
        234     )
        236     if downloader is None:

    File /usr/lib/python3/dist-packages/pooch/utils.py:276, in make_local_storage(path, env)
        272 if env is not None:
        273     message.append(
        274         f"Use environment variable '{env}' to specify a different location."
        275     )
    --> 276 raise PermissionError(" ".join(message)) from error

    PermissionError: [Errno 13] Permission denied: '/sbuild-nonexistent' | Pooch could not create data cache folder '/sbuild-nonexistent/.cache/xarray_tutorial_data'. Will not be able to download data files.

## Multiple plots and map projections

Control the map projection parameters on multiple axes

This example illustrates how to plot multiple maps and control their extent and aspect ratio.

For more details see this discussion on github.

    [3]:

    air = ds.air.isel(time=[0, 724]) - 273.15

    # This is the map projection we want to plot *onto*
    map_proj = ccrs.LambertConformal(central_longitude=-95, central_latitude=45)

    p = air.plot(
        transform=ccrs.PlateCarree(),  # the data's projection
        col="time",
        col_wrap=1,  # multiplot settings
        aspect=ds.dims["lon"] / ds.dims["lat"],  # for a sensible figsize
        subplot_kws={"projection": map_proj},
    )  # the plot's projection

    # We have to set the map's options on all axes
    for ax in p.axes.flat:
        ax.coastlines()
        ax.set_extent([-160, -30, 5, 75])

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[3], line 1
    ----> 1 air = ds.air.isel(time=[0, 724]) - 273.15
          3 # This is the map projection we want to plot *onto*
          4 map_proj = ccrs.LambertConformal(central_longitude=-95, central_latitude=45)

    NameError: name 'ds' is not defined

## Centered colormaps

Xarray’s automatic colormaps choice

    [4]:

    air = ds.air.isel(time=0)

    f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 6))

    # The first plot (in kelvins) chooses "viridis" and uses the data's min/max
    air.plot(ax=ax1, cbar_kwargs={"label": "K"})
    ax1.set_title("Kelvins: default")
    ax2.set_xlabel("")

    # The second plot (in celsius) now chooses "BuRd" and centers min/max around 0
    airc = air - 273.15
    airc.plot(ax=ax2, cbar_kwargs={"label": "°C"})
    ax2.set_title("Celsius: default")
    ax2.set_xlabel("")
    ax2.set_ylabel("")

    # The center doesn't have to be 0
    air.plot(ax=ax3, center=273.15, cbar_kwargs={"label": "K"})
    ax3.set_title("Kelvins: center=273.15")

    # Or it can be ignored
    airc.plot(ax=ax4, center=False, cbar_kwargs={"label": "°C"})
    ax4.set_title("Celsius: center=False")
    ax4.set_ylabel("")

    # Make it nice
    plt.tight_layout()

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[4], line 1
    ----> 1 air = ds.air.isel(time=0)
          3 f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 6))
          5 # The first plot (in kelvins) chooses "viridis" and uses the data's min/max

    NameError: name 'ds' is not defined

## Control the plot’s colorbar

Use `cbar_kwargs` keyword to specify the number of ticks. The `spacing` kwarg can be used to draw proportional ticks.

    [5]:

    air2d = ds.air.isel(time=500)

    # Prepare the figure
    f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(14, 4))

    # Irregular levels to illustrate the use of a proportional colorbar
    levels = [245, 250, 255, 260, 265, 270, 275, 280, 285, 290, 310, 340]

    # Plot data
    air2d.plot(ax=ax1, levels=levels)
    air2d.plot(ax=ax2, levels=levels, cbar_kwargs={"ticks": levels})
    air2d.plot(
        ax=ax3, levels=levels, cbar_kwargs={"ticks": levels, "spacing": "proportional"}
    )

    # Show plots
    plt.tight_layout()

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[5], line 1
    ----> 1 air2d = ds.air.isel(time=500)
          3 # Prepare the figure
          4 f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(14, 4))

    NameError: name 'ds' is not defined

## Multiple lines from a 2d DataArray

Use `xarray.plot.line` on a 2d DataArray to plot selections as multiple lines.

See `plotting.multiplelines` for more details.

    [6]:

    air = ds.air - 273.15  # to celsius

    # Prepare the figure
    f, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharey=True)

    # Selected latitude indices
    isel_lats = [10, 15, 20]

    # Temperature vs longitude plot - illustrates the "hue" kwarg
    air.isel(time=0, lat=isel_lats).plot.line(ax=ax1, hue="lat")
    ax1.set_ylabel("°C")

    # Temperature vs time plot - illustrates the "x" and "add_legend" kwargs
    air.isel(lon=30, lat=isel_lats).plot.line(ax=ax2, x="time", add_legend=False)
    ax2.set_ylabel("")

    # Show
    plt.tight_layout()

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[6], line 1
    ----> 1 air = ds.air - 273.15  # to celsius
          3 # Prepare the figure
          4 f, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharey=True)

    NameError: name 'ds' is not defined