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')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-2-15c698672cac> in <module>
----> 1 ds = xr.tutorial.load_dataset('air_temperature')
/build/python-xarray-fVjOFI/python-xarray-0.15.1/xarray/tutorial.py in load_dataset(*args, **kwargs)
111 open_dataset
112 """
--> 113 with open_dataset(*args, **kwargs) as ds:
114 return ds.load()
115
/build/python-xarray-fVjOFI/python-xarray-0.15.1/xarray/tutorial.py in open_dataset(name, cache, cache_dir, github_url, branch, **kws)
76 # May want to add an option to remove it.
77 if not _os.path.isdir(longdir):
---> 78 _os.mkdir(longdir)
79
80 url = "/".join((github_url, "raw", branch, fullname))
FileNotFoundError: [Errno 2] No such file or directory: '/sbuild-nonexistent/.xarray_tutorial_data'
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)
<ipython-input-3-91c1107c19c0> in <module>
----> 1 air = ds.air.isel(time=[0, 724]) - 273.15
2
3 # This is the map projection we want to plot *onto*
4 map_proj = ccrs.LambertConformal(central_longitude=-95, central_latitude=45)
5
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)
<ipython-input-4-13691d1c0109> in <module>
----> 1 air = ds.air.isel(time=0)
2
3 f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 6))
4
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)
<ipython-input-5-eefd6d2158f3> in <module>
----> 1 air2d = ds.air.isel(time=500)
2
3 # Prepare the figure
4 f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(14, 4))
5
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)
<ipython-input-6-2c471b645252> in <module>
----> 1 air = ds.air - 273.15 # to celsius
2
3 # Prepare the figure
4 f, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharey=True)
5
NameError: name 'ds' is not defined
imshow()
and rasterio map projections¶
Using rasterio’s projection information for more accurate plots.
This example extends recipes.rasterio
and plots the image in the original map projection instead of relying on pcolormesh and a map transformation.
[7]:
url = 'https://github.com/mapbox/rasterio/raw/master/tests/data/RGB.byte.tif'
da = xr.open_rasterio(url)
# The data is in UTM projection. We have to set it manually until
# https://github.com/SciTools/cartopy/issues/813 is implemented
crs = ccrs.UTM('18N')
# Plot on a map
ax = plt.subplot(projection=crs)
da.plot.imshow(ax=ax, rgb='band', transform=crs)
ax.coastlines('10m', color='r')
[7]:
<cartopy.mpl.feature_artist.FeatureArtist at 0x7f74090b5370>
---------------------------------------------------------------------------
PermissionError Traceback (most recent call last)
/usr/lib/python3/dist-packages/IPython/core/formatters.py in __call__(self, obj)
339 pass
340 else:
--> 341 return printer(obj)
342 # Finally look for special method names
343 method = get_real_method(obj, self.print_method)
/usr/lib/python3/dist-packages/IPython/core/pylabtools.py in <lambda>(fig)
246
247 if 'png' in formats:
--> 248 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
249 if 'retina' in formats or 'png2x' in formats:
250 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
/usr/lib/python3/dist-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
130 FigureCanvasBase(fig)
131
--> 132 fig.canvas.print_figure(bytes_io, **kw)
133 data = bytes_io.getvalue()
134 if fmt == 'svg':
/usr/lib/python3/dist-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
2077 print_method, dpi=dpi, orientation=orientation),
2078 draw_disabled=True)
-> 2079 self.figure.draw(renderer)
2080 bbox_artists = kwargs.pop("bbox_extra_artists", None)
2081 bbox_inches = self.figure.get_tightbbox(renderer,
/usr/lib/python3/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
36 renderer.start_filter()
37
---> 38 return draw(artist, renderer, *args, **kwargs)
39 finally:
40 if artist.get_agg_filter() is not None:
/usr/lib/python3/dist-packages/matplotlib/figure.py in draw(self, renderer)
1733
1734 self.patch.draw(renderer)
-> 1735 mimage._draw_list_compositing_images(
1736 renderer, self, artists, self.suppressComposite)
1737
/usr/lib/python3/dist-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
135 if not_composite or not has_images:
136 for a in artists:
--> 137 a.draw(renderer)
138 else:
139 # Composite any adjacent images together
/usr/lib/python3/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
36 renderer.start_filter()
37
---> 38 return draw(artist, renderer, *args, **kwargs)
39 finally:
40 if artist.get_agg_filter() is not None:
/usr/lib/python3/dist-packages/cartopy/mpl/geoaxes.py in draw(self, renderer, inframe)
385 self._done_img_factory = True
386
--> 387 return matplotlib.axes.Axes.draw(self, renderer=renderer,
388 inframe=inframe)
389
/usr/lib/python3/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
36 renderer.start_filter()
37
---> 38 return draw(artist, renderer, *args, **kwargs)
39 finally:
40 if artist.get_agg_filter() is not None:
/usr/lib/python3/dist-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
2628 renderer.stop_rasterizing()
2629
-> 2630 mimage._draw_list_compositing_images(renderer, self, artists)
2631
2632 renderer.close_group('axes')
/usr/lib/python3/dist-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
135 if not_composite or not has_images:
136 for a in artists:
--> 137 a.draw(renderer)
138 else:
139 # Composite any adjacent images together
/usr/lib/python3/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
36 renderer.start_filter()
37
---> 38 return draw(artist, renderer, *args, **kwargs)
39 finally:
40 if artist.get_agg_filter() is not None:
/usr/lib/python3/dist-packages/cartopy/mpl/feature_artist.py in draw(self, renderer, *args, **kwargs)
162 except ValueError:
163 warnings.warn('Unable to determine extent. Defaulting to global.')
--> 164 geoms = self._feature.intersecting_geometries(extent)
165
166 # Combine all the keyword args in priority order.
/usr/lib/python3/dist-packages/cartopy/feature/__init__.py in intersecting_geometries(self, extent)
301 """
302 self.scaler.scale_from_extent(extent)
--> 303 return super(NaturalEarthFeature, self).intersecting_geometries(extent)
304
305 def with_scale(self, new_scale):
/usr/lib/python3/dist-packages/cartopy/feature/__init__.py in intersecting_geometries(self, extent)
118 extent_geom = sgeom.box(extent[0], extent[2],
119 extent[1], extent[3])
--> 120 return (geom for geom in self.geometries() if
121 geom is not None and extent_geom.intersects(geom))
122 else:
/usr/lib/python3/dist-packages/cartopy/feature/__init__.py in geometries(self)
283 key = (self.name, self.category, self.scale)
284 if key not in _NATURAL_EARTH_GEOM_CACHE:
--> 285 path = shapereader.natural_earth(resolution=self.scale,
286 category=self.category,
287 name=self.name)
/usr/lib/python3/dist-packages/cartopy/io/shapereader.py in natural_earth(resolution, category, name)
357 format_dict = {'config': config, 'category': category,
358 'name': name, 'resolution': resolution}
--> 359 return ne_downloader.path(format_dict)
360
361
/usr/lib/python3/dist-packages/cartopy/io/__init__.py in path(self, format_dict)
220 else:
221 # we need to download the file
--> 222 result_path = self.acquire_resource(target_path, format_dict)
223
224 return result_path
/usr/lib/python3/dist-packages/cartopy/io/shapereader.py in acquire_resource(self, target_path, format_dict)
408 target_dir = os.path.dirname(target_path)
409 if not os.path.isdir(target_dir):
--> 410 os.makedirs(target_dir)
411
412 url = self.url(format_dict)
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
221 return
222 try:
--> 223 mkdir(name, mode)
224 except OSError:
225 # Cannot rely on checking for EEXIST, since the operating system
PermissionError: [Errno 13] Permission denied: '/sbuild-nonexistent'
<Figure size 432x288 with 1 Axes>
Parsing rasterio geocoordinates¶
Converting a projection’s cartesian coordinates into 2D longitudes and latitudes.
These new coordinates might be handy for plotting and indexing, but it should be kept in mind that a grid which is regular in projection coordinates will likely be irregular in lon/lat. It is often recommended to work in the data’s original map projection (see recipes.rasterio_rgb
).
[8]:
from rasterio.warp import transform
import numpy as np
url = 'https://github.com/mapbox/rasterio/raw/master/tests/data/RGB.byte.tif'
da = xr.open_rasterio(url)
# Compute the lon/lat coordinates with rasterio.warp.transform
ny, nx = len(da['y']), len(da['x'])
x, y = np.meshgrid(da['x'], da['y'])
# Rasterio works with 1D arrays
lon, lat = transform(da.crs, {'init': 'EPSG:4326'},
x.flatten(), y.flatten())
lon = np.asarray(lon).reshape((ny, nx))
lat = np.asarray(lat).reshape((ny, nx))
da.coords['lon'] = (('y', 'x'), lon)
da.coords['lat'] = (('y', 'x'), lat)
# Compute a greyscale out of the rgb image
greyscale = da.mean(dim='band')
# Plot on a map
ax = plt.subplot(projection=ccrs.PlateCarree())
greyscale.plot(ax=ax, x='lon', y='lat', transform=ccrs.PlateCarree(),
cmap='Greys_r', add_colorbar=False)
ax.coastlines('10m', color='r')
[8]:
<cartopy.mpl.feature_artist.FeatureArtist at 0x7f7408dd1ee0>
---------------------------------------------------------------------------
PermissionError Traceback (most recent call last)
/usr/lib/python3/dist-packages/IPython/core/formatters.py in __call__(self, obj)
339 pass
340 else:
--> 341 return printer(obj)
342 # Finally look for special method names
343 method = get_real_method(obj, self.print_method)
/usr/lib/python3/dist-packages/IPython/core/pylabtools.py in <lambda>(fig)
246
247 if 'png' in formats:
--> 248 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
249 if 'retina' in formats or 'png2x' in formats:
250 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
/usr/lib/python3/dist-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
130 FigureCanvasBase(fig)
131
--> 132 fig.canvas.print_figure(bytes_io, **kw)
133 data = bytes_io.getvalue()
134 if fmt == 'svg':
/usr/lib/python3/dist-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
2077 print_method, dpi=dpi, orientation=orientation),
2078 draw_disabled=True)
-> 2079 self.figure.draw(renderer)
2080 bbox_artists = kwargs.pop("bbox_extra_artists", None)
2081 bbox_inches = self.figure.get_tightbbox(renderer,
/usr/lib/python3/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
36 renderer.start_filter()
37
---> 38 return draw(artist, renderer, *args, **kwargs)
39 finally:
40 if artist.get_agg_filter() is not None:
/usr/lib/python3/dist-packages/matplotlib/figure.py in draw(self, renderer)
1733
1734 self.patch.draw(renderer)
-> 1735 mimage._draw_list_compositing_images(
1736 renderer, self, artists, self.suppressComposite)
1737
/usr/lib/python3/dist-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
135 if not_composite or not has_images:
136 for a in artists:
--> 137 a.draw(renderer)
138 else:
139 # Composite any adjacent images together
/usr/lib/python3/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
36 renderer.start_filter()
37
---> 38 return draw(artist, renderer, *args, **kwargs)
39 finally:
40 if artist.get_agg_filter() is not None:
/usr/lib/python3/dist-packages/cartopy/mpl/geoaxes.py in draw(self, renderer, inframe)
385 self._done_img_factory = True
386
--> 387 return matplotlib.axes.Axes.draw(self, renderer=renderer,
388 inframe=inframe)
389
/usr/lib/python3/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
36 renderer.start_filter()
37
---> 38 return draw(artist, renderer, *args, **kwargs)
39 finally:
40 if artist.get_agg_filter() is not None:
/usr/lib/python3/dist-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
2628 renderer.stop_rasterizing()
2629
-> 2630 mimage._draw_list_compositing_images(renderer, self, artists)
2631
2632 renderer.close_group('axes')
/usr/lib/python3/dist-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
135 if not_composite or not has_images:
136 for a in artists:
--> 137 a.draw(renderer)
138 else:
139 # Composite any adjacent images together
/usr/lib/python3/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
36 renderer.start_filter()
37
---> 38 return draw(artist, renderer, *args, **kwargs)
39 finally:
40 if artist.get_agg_filter() is not None:
/usr/lib/python3/dist-packages/cartopy/mpl/feature_artist.py in draw(self, renderer, *args, **kwargs)
162 except ValueError:
163 warnings.warn('Unable to determine extent. Defaulting to global.')
--> 164 geoms = self._feature.intersecting_geometries(extent)
165
166 # Combine all the keyword args in priority order.
/usr/lib/python3/dist-packages/cartopy/feature/__init__.py in intersecting_geometries(self, extent)
301 """
302 self.scaler.scale_from_extent(extent)
--> 303 return super(NaturalEarthFeature, self).intersecting_geometries(extent)
304
305 def with_scale(self, new_scale):
/usr/lib/python3/dist-packages/cartopy/feature/__init__.py in intersecting_geometries(self, extent)
118 extent_geom = sgeom.box(extent[0], extent[2],
119 extent[1], extent[3])
--> 120 return (geom for geom in self.geometries() if
121 geom is not None and extent_geom.intersects(geom))
122 else:
/usr/lib/python3/dist-packages/cartopy/feature/__init__.py in geometries(self)
283 key = (self.name, self.category, self.scale)
284 if key not in _NATURAL_EARTH_GEOM_CACHE:
--> 285 path = shapereader.natural_earth(resolution=self.scale,
286 category=self.category,
287 name=self.name)
/usr/lib/python3/dist-packages/cartopy/io/shapereader.py in natural_earth(resolution, category, name)
357 format_dict = {'config': config, 'category': category,
358 'name': name, 'resolution': resolution}
--> 359 return ne_downloader.path(format_dict)
360
361
/usr/lib/python3/dist-packages/cartopy/io/__init__.py in path(self, format_dict)
220 else:
221 # we need to download the file
--> 222 result_path = self.acquire_resource(target_path, format_dict)
223
224 return result_path
/usr/lib/python3/dist-packages/cartopy/io/shapereader.py in acquire_resource(self, target_path, format_dict)
408 target_dir = os.path.dirname(target_path)
409 if not os.path.isdir(target_dir):
--> 410 os.makedirs(target_dir)
411
412 url = self.url(format_dict)
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
211 if head and tail and not path.exists(head):
212 try:
--> 213 makedirs(head, exist_ok=exist_ok)
214 except FileExistsError:
215 # Defeats race condition when another thread created the path
/usr/lib/python3.8/os.py in makedirs(name, mode, exist_ok)
221 return
222 try:
--> 223 mkdir(name, mode)
224 except OSError:
225 # Cannot rely on checking for EEXIST, since the operating system
PermissionError: [Errno 13] Permission denied: '/sbuild-nonexistent'
<Figure size 432x288 with 1 Axes>