Plotting

Introduction

Labeled data enables expressive computations. These samelabels can also be used to easily create informative plots.

xarray’s plotting capabilities are centered aroundxarray.DataArray objects.To plot xarray.Dataset objectssimply access the relevant DataArrays, ie dset['var1'].Here we focus mostly on arrays 2d or larger. If your data fitsnicely into a pandas DataFrame then you’re better off using one of the moredeveloped tools there.

xarray plotting functionality is a thin wrapper around the popularmatplotlib library.Matplotlib syntax and function names were copied as much as possible, whichmakes for an easy transition between the two.Matplotlib must be installed before xarray can plot.

To use xarray’s plotting capabilities with time coordinates containingcftime.datetime objectsnc-time-axis v1.2.0 or laterneeds to be installed.

For more extensive plotting applications consider the following projects:

  • Seaborn: “providesa high-level interface for drawing attractive statistical graphics.”Integrates well with pandas.

  • HoloViewsand GeoViews: “Composable, declarativedata structures for building even complex visualizations easily.” Includesnative support for xarray objects.

  • hvplot: hvplot makes it very easy to producedynamic plots (backed by Holoviews or Geoviews) by adding a hvplotaccessor to DataArrays.

  • Cartopy: Provides cartographictools.

Imports

The following imports are necessary for all of the examples.

  1. In [1]: import numpy as np
  2.  
  3. In [2]: import pandas as pd
  4.  
  5. In [3]: import matplotlib.pyplot as plt
  6.  
  7. In [4]: import xarray as xr

For these examples we’ll use the North American air temperature dataset.

  1. In [5]: airtemps = xr.tutorial.open_dataset('air_temperature')
  2.  
  3. In [6]: airtemps
  4. Out[6]:
  5. <xarray.Dataset>
  6. Dimensions: (lat: 25, lon: 53, time: 2920)
  7. Coordinates:
  8. * lat (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  9. * lon (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
  10. * time (time) datetime64[ns] 2013-01-01 ... 2014-12-31T18:00:00
  11. Data variables:
  12. air (time, lat, lon) float32 ...
  13. Attributes:
  14. Conventions: COARDS
  15. title: 4x daily NMC reanalysis (1948)
  16. description: Data is from NMC initialized reanalysis\n(4x/day). These a...
  17. platform: Model
  18. references: http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanaly...
  19.  
  20. # Convert to celsius
  21. In [7]: air = airtemps.air - 273.15
  22.  
  23. # copy attributes to get nice figure labels and change Kelvin to Celsius
  24. In [8]: air.attrs = airtemps.air.attrs
  25.  
  26. In [9]: air.attrs['units'] = 'deg C'

Note

Until GH1614 is solved, you might need to copy over the metadata in attrs to get informative figure labels (as was done above).

One Dimension

Simple Example

The simplest way to make a plot is to call the xarray.DataArray.plot() method.

  1. In [10]: air1d = air.isel(lat=10, lon=10)
  2.  
  3. In [11]: air1d.plot()
  4. Out[11]: [<matplotlib.lines.Line2D at 0x7f34243f3080>]

_images/plotting_1d_simple.pngxarray uses the coordinate name along with metadata attrs.long_name, attrs.standard_name, DataArray.name and attrs.units (if available) to label the axes. The names long_name, standard_name and units are copied from the CF-conventions spec. When choosing names, the order of precedence is long_name, standard_name and finally DataArray.name. The y-axis label in the above plot was constructed from the long_name and units attributes of air1d.

  1. In [12]: air1d.attrs
  2. Out[12]:
  3. OrderedDict([('long_name', '4xDaily Air temperature at sigma level 995'),
  4. ('units', 'deg C'),
  5. ('precision', 2),
  6. ('GRIB_id', 11),
  7. ('GRIB_name', 'TMP'),
  8. ('var_desc', 'Air temperature'),
  9. ('dataset', 'NMC Reanalysis'),
  10. ('level_desc', 'Surface'),
  11. ('statistic', 'Individual Obs'),
  12. ('parent_stat', 'Other'),
  13. ('actual_range', array([185.16, 322.1 ], dtype=float32))])

Additional Arguments

Additional arguments are passed directly to the matplotlib function whichdoes the work.For example, xarray.plot.line() callsmatplotlib.pyplot.plot passing in the index and the array values as x and y, respectively.So to make a line plot with blue triangles a matplotlib format stringcan be used:

  1. In [13]: air1d[:200].plot.line('b-^')
  2. Out[13]: [<matplotlib.lines.Line2D at 0x7f34252b1e48>]

_images/plotting_1d_additional_args.png

Note

Not all xarray plotting methods support passing positional argumentsto the wrapped matplotlib functions, but they do allsupport keyword arguments.

Keyword arguments work the same way, and are more explicit.

  1. In [14]: air1d[:200].plot.line(color='purple', marker='o')
  2. Out[14]: [<matplotlib.lines.Line2D at 0x7f3424fe5be0>]

_images/plotting_example_sin3.png

Adding to Existing Axis

To add the plot to an existing axis pass in the axis as a keyword argumentax. This works for all xarray plotting methods.In this example axes is an array consisting of the left and rightaxes created by plt.subplots.

  1. In [15]: fig, axes = plt.subplots(ncols=2)
  2.  
  3. In [16]: axes
  4. Out[16]:
  5. array([<matplotlib.axes._subplots.AxesSubplot object at 0x7f3424e57320>,
  6. <matplotlib.axes._subplots.AxesSubplot object at 0x7f3425425160>], dtype=object)
  7.  
  8. In [17]: air1d.plot(ax=axes[0])
  9. Out[17]: [<matplotlib.lines.Line2D at 0x7f342513e400>]
  10.  
  11. In [18]: air1d.plot.hist(ax=axes[1])
  12. Out[18]:
  13. (array([ 9., 38., 255., 584., 542., 489., 368., 258., 327., 50.]),
  14. array([ 0.95 , 2.719, 4.488, ..., 15.102, 16.871, 18.64 ], dtype=float32),
  15. <a list of 10 Patch objects>)
  16.  
  17. In [19]: plt.tight_layout()
  18.  
  19. In [20]: plt.draw()

_images/plotting_example_existing_axes.pngOn the right is a histogram created by xarray.plot.hist().

Controlling the figure size

You can pass a figsize argument to all xarray’s plotting methods tocontrol the figure size. For convenience, xarray’s plotting methods alsosupport the aspect and size arguments which control the size of theresulting image via the formula figsize = (aspect * size, size):

  1. In [21]: air1d.plot(aspect=2, size=3)
  2. Out[21]: [<matplotlib.lines.Line2D at 0x7f342579aeb8>]
  3.  
  4. In [22]: plt.tight_layout()

_images/plotting_example_size_and_aspect.pngThis feature also works with Faceting. For facet plots,size and aspect refer to a single panel (so that aspect * sizegives the width of each facet in inches), while figsize refers to theentire figure (as for matplotlib’s figsize argument).

Note

If figsize or size are used, a new figure is created,so this is mutually exclusive with the ax argument.

Note

The convention used by xarray (figsize = (aspect * size, size)) isborrowed from seaborn: it is therefore not equivalent to matplotlib’s.

Multiple lines showing variation along a dimension

It is possible to make line plots of two-dimensional data by calling xarray.plot.line()with appropriate arguments. Consider the 3D variable air defined above. We can use lineplots to check the variation of air temperature at three different latitudes along a longitude line:

  1. In [23]: air.isel(lon=10, lat=[19,21,22]).plot.line(x='time')
  2. Out[23]:
  3. [<matplotlib.lines.Line2D at 0x7f342572b710>,
  4. <matplotlib.lines.Line2D at 0x7f34257c3c50>,
  5. <matplotlib.lines.Line2D at 0x7f34257c3080>]

_images/plotting_example_multiple_lines_x_kwarg.pngIt is required to explicitly specify either

  • x: the dimension to be used for the x-axis, or

  • hue: the dimension you want to represent by multiple lines.

Thus, we could have made the previous plot by specifying hue='lat' instead of x='time'.If required, the automatic legend can be turned off using addlegend=False. Alternatively,hue can be passed directly to xarray.plot() as _air.isel(lon=10, lat=[19,21,22]).plot(hue=’lat’).

Dimension along y-axis

It is also possible to make line plots such that the data are on the x-axis and a dimension is on the y-axis. This can be done by specifying the appropriate y keyword argument.

  1. In [24]: air.isel(time=10, lon=[10, 11]).plot(y='lat', hue='lon')
  2. Out[24]:
  3. [<matplotlib.lines.Line2D at 0x7f34258ab908>,
  4. <matplotlib.lines.Line2D at 0x7f34258abeb8>]

_images/plotting_example_xy_kwarg.png

Step plots

As an alternative, also a step plot similar to matplotlib’s plt.step can bemade using 1D data.

  1. In [25]: air1d[:20].plot.step(where='mid')
  2. Out[25]: [<matplotlib.lines.Line2D at 0x7f3425811da0>]

_images/plotting_example_step.pngThe argument where defines where the steps should be placed, options are'pre' (default), 'post', and 'mid'. This is particularly handywhen plotting data grouped with xarray.Dataset.groupby_bins().

  1. In [26]: air_grp = air.mean(['time','lon']).groupby_bins('lat',[0,23.5,66.5,90])
  2.  
  3. In [27]: air_mean = air_grp.mean()
  4.  
  5. In [28]: air_std = air_grp.std()
  6.  
  7. In [29]: air_mean.plot.step()
  8. Out[29]: [<matplotlib.lines.Line2D at 0x7f342595f3c8>]
  9.  
  10. In [30]: (air_mean + air_std).plot.step(ls=':')
  11. Out[30]: [<matplotlib.lines.Line2D at 0x7f34259b8ac8>]
  12.  
  13. In [31]: (air_mean - air_std).plot.step(ls=':')
  14. Out[31]: [<matplotlib.lines.Line2D at 0x7f34259b82e8>]
  15.  
  16. In [32]: plt.ylim(-20,30)
  17. Out[32]: (-20, 30)
  18.  
  19. In [33]: plt.title('Zonal mean temperature')
  20. Out[33]: Text(0.5, 1.0, 'Zonal mean temperature')

_images/plotting_example_step_groupby.pngIn this case, the actual boundaries of the bins are used and the where argumentis ignored.

Other axes kwargs

The keyword arguments xincrease and yincrease let you control the axes direction.

  1. In [34]: air.isel(time=10, lon=[10, 11]).plot.line(y='lat', hue='lon', xincrease=False, yincrease=False)
  2. Out[34]:
  3. [<matplotlib.lines.Line2D at 0x7f3425a2af98>,
  4. <matplotlib.lines.Line2D at 0x7f3425a2ac18>]

_images/plotting_example_xincrease_yincrease_kwarg.pngIn addition, one can use xscale, yscale to set axes scaling; xticks, yticks to set axes ticks and xlim, ylim to set axes limits. These accept the same values as the matplotlib methods Axes.set(x,y)scale(), Axes.set(x,y)ticks(), Axes.set_(x,y)lim() respectively.

Two Dimensions

Simple Example

The default method xarray.DataArray.plot() calls xarray.plot.pcolormesh() by default when the data is two-dimensional.

  1. In [35]: air2d = air.isel(time=500)
  2.  
  3. In [36]: air2d.plot()
  4. Out[36]: <matplotlib.collections.QuadMesh at 0x7f3424691f28>

_images/2d_simple.pngAll 2d plots in xarray allow the use of the keyword arguments yincreaseand xincrease.

  1. In [37]: air2d.plot(yincrease=False)
  2. Out[37]: <matplotlib.collections.QuadMesh at 0x7f3425bd0080>

_images/2d_simple_yincrease.png

Note

We use xarray.plot.pcolormesh() as the default two-dimensional plotmethod because it is more flexible than xarray.plot.imshow().However, for large arrays, imshow can be much faster than pcolormesh.If speed is important to you and you are plotting a regular mesh, considerusing imshow.

Missing Values

xarray plots data with Missing values.

  1. In [38]: bad_air2d = air2d.copy()
  2.  
  3. In [39]: bad_air2d[dict(lat=slice(0, 10), lon=slice(0, 25))] = np.nan
  4.  
  5. In [40]: bad_air2d.plot()
  6. Out[40]: <matplotlib.collections.QuadMesh at 0x7f33f35b5cc0>

_images/plotting_missing_values.png

Nonuniform Coordinates

It’s not necessary for the coordinates to be evenly spaced. Bothxarray.plot.pcolormesh() (default) and xarray.plot.contourf() canproduce plots with nonuniform coordinates.

  1. In [41]: b = air2d.copy()
  2.  
  3. # Apply a nonlinear transformation to one of the coords
  4. In [42]: b.coords['lat'] = np.log(b.coords['lat'])
  5.  
  6. In [43]: b.plot()
  7. Out[43]: <matplotlib.collections.QuadMesh at 0x7f33f357e8d0>

_images/plotting_nonuniform_coords.png

Calling Matplotlib

Since this is a thin wrapper around matplotlib, all the functionality ofmatplotlib is available.

  1. In [44]: air2d.plot(cmap=plt.cm.Blues)
  2. Out[44]: <matplotlib.collections.QuadMesh at 0x7f33f34db7f0>
  3.  
  4. In [45]: plt.title('These colors prove North America\nhas fallen in the ocean')
  5. Out[45]: Text(0.5, 1.0, 'These colors prove North America\nhas fallen in the ocean')
  6.  
  7. In [46]: plt.ylabel('latitude')
  8. Out[46]: Text(0, 0.5, 'latitude')
  9.  
  10. In [47]: plt.xlabel('longitude')
  11. Out[47]: Text(0.5, 0, 'longitude')
  12.  
  13. In [48]: plt.tight_layout()
  14.  
  15. In [49]: plt.draw()

_images/plotting_2d_call_matplotlib.png

Note

xarray methods update label information and generally play around with theaxes. So any kind of updates to the plotshould be done after the call to the xarray’s plot.In the example below, plt.xlabel effectively does nothing, sinced_ylog.plot() updates the xlabel.

  1. In [50]: plt.xlabel('Never gonna see this.')
  2. Out[50]: Text(0.5, 0, 'Never gonna see this.')
  3.  
  4. In [51]: air2d.plot()
  5. Out[51]: <matplotlib.collections.QuadMesh at 0x7f33f344a160>
  6.  
  7. In [52]: plt.draw()

_images/plotting_2d_call_matplotlib2.png

Colormaps

xarray borrows logic from Seaborn to infer what kind of color map to use. Forexample, consider the original data in Kelvins rather than Celsius:

  1. In [53]: airtemps.air.isel(time=0).plot()
  2. Out[53]: <matplotlib.collections.QuadMesh at 0x7f33f33cf358>

_images/plotting_kelvin.pngThe Celsius data contain 0, so a diverging color map was used. TheKelvins do not have 0, so the default color map was used.

Robust

Outliers often have an extreme effect on the output of the plot.Here we add two bad data points. This affects the color scale,washing out the plot.

  1. In [54]: air_outliers = airtemps.air.isel(time=0).copy()
  2.  
  3. In [55]: air_outliers[0, 0] = 100
  4.  
  5. In [56]: air_outliers[-1, -1] = 400
  6.  
  7. In [57]: air_outliers.plot()
  8. Out[57]: <matplotlib.collections.QuadMesh at 0x7f33f33a0ef0>

_images/plotting_robust1.pngThis plot shows that we have outliers. The easy way to visualizethe data without the outliers is to pass the parameterrobust=True.This will use the 2nd and 98thpercentiles of the data to compute the color limits.

  1. In [58]: air_outliers.plot(robust=True)
  2. Out[58]: <matplotlib.collections.QuadMesh at 0x7f33f3383cc0>

_images/plotting_robust2.pngObserve that the ranges of the color bar have changed. The arrows on thecolor bar indicatethat the colors include data points outside the bounds.

Discrete Colormaps

It is often useful, when visualizing 2d data, to use a discrete colormap,rather than the default continuous colormaps that matplotlib uses. Thelevels keyword argument can be used to generate plots with discretecolormaps. For example, to make a plot with 8 discrete color intervals:

  1. In [59]: air2d.plot(levels=8)
  2. Out[59]: <matplotlib.collections.QuadMesh at 0x7f33f32864a8>

_images/plotting_discrete_levels.pngIt is also possible to use a list of levels to specify the boundaries of thediscrete colormap:

  1. In [60]: air2d.plot(levels=[0, 12, 18, 30])
  2. Out[60]: <matplotlib.collections.QuadMesh at 0x7f33f3267748>

_images/plotting_listed_levels.pngYou can also specify a list of discrete colors through the colors argument:

  1. In [61]: flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
  2.  
  3. In [62]: air2d.plot(levels=[0, 12, 18, 30], colors=flatui)
  4. Out[62]: <matplotlib.collections.QuadMesh at 0x7f33f323cc50>

_images/plotting_custom_colors_levels.pngFinally, if you have Seaborninstalled, you can also specify a seaborn color palette to the cmapargument. Note that levels must be specified with seaborn color palettesif using imshow or pcolormesh (but not with contour or contourf,since levels are chosen automatically).

  1. In [63]: air2d.plot(levels=10, cmap='husl')
  2. Out[63]: <matplotlib.collections.QuadMesh at 0x7f33f31c1198>
  3.  
  4. In [64]: plt.draw()

_images/plotting_seaborn_palette.png

Faceting

Faceting here refers to splitting an array along one or two dimensions andplotting each group.xarray’s basic plotting is useful for plotting two dimensional arrays. Whatabout three or four dimensional arrays? That’s where facets become helpful.

Consider the temperature data set. There are 4 observations per day for twoyears which makes for 2920 values along the time dimension.One way to visualize this data is to make aseparate plot for each time period.

The faceted dimension should not have too many values;faceting on the time dimension will produce 2920 plots. That’stoo much to be helpful. To handle this situation try performingan operation that reduces the size of the data in some way. For example, wecould compute the average air temperature for each month and reduce thesize of this dimension from 2920 -> 12. A simpler way isto just take a slice on that dimension.So let’s use a slice to pick 6 times throughout the first year.

  1. In [65]: t = air.isel(time=slice(0, 365 * 4, 250))
  2.  
  3. In [66]: t.coords
  4. Out[66]:
  5. Coordinates:
  6. * lat (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  7. * lon (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
  8. * time (time) datetime64[ns] 2013-01-01 ... 2013-11-09T12:00:00

Simple Example

The easiest way to create faceted plots is to pass in row or colarguments to the xarray plotting methods/functions. This returns axarray.plot.FacetGrid object.

  1. In [67]: g_simple = t.plot(x='lon', y='lat', col='time', col_wrap=3)

_images/plot_facet_dataarray.pngFaceting also works for line plots.

  1. In [68]: g_simple_line = t.isel(lat=slice(0,None,4)).plot(x='lon', hue='lat', col='time', col_wrap=3)

_images/plot_facet_dataarray_line.png

4 dimensional

For 4 dimensional arrays we can use the rows and columns of the grids.Here we create a 4 dimensional array by taking the original data and addinga fixed amount. Now we can see how the temperature maps would compare ifone were much hotter.

  1. In [69]: t2 = t.isel(time=slice(0, 2))
  2.  
  3. In [70]: t4d = xr.concat([t2, t2 + 40], pd.Index(['normal', 'hot'], name='fourth_dim'))
  4.  
  5. # This is a 4d array
  6. In [71]: t4d.coords
  7. Out[71]:
  8. Coordinates:
  9. * lat (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 22.5 20.0 17.5 15.0
  10. * lon (lon) float32 200.0 202.5 205.0 207.5 ... 325.0 327.5 330.0
  11. * time (time) datetime64[ns] 2013-01-01 2013-03-04T12:00:00
  12. * fourth_dim (fourth_dim) object 'normal' 'hot'
  13.  
  14. In [72]: t4d.plot(x='lon', y='lat', col='time', row='fourth_dim')
  15. Out[72]: <xarray.plot.facetgrid.FacetGrid at 0x7f33f302c128>

_images/plot_facet_4d.png

Other features

Faceted plotting supports other arguments common to xarray 2d plots.

  1. In [73]: hasoutliers = t.isel(time=slice(0, 5)).copy()
  2.  
  3. In [74]: hasoutliers[0, 0, 0] = -100
  4.  
  5. In [75]: hasoutliers[-1, -1, -1] = 400
  6.  
  7. In [76]: g = hasoutliers.plot.pcolormesh('lon', 'lat', col='time', col_wrap=3,
  8. ....: robust=True, cmap='viridis',
  9. ....: cbar_kwargs={'label': 'this has outliers'})
  10. ....:

_images/plot_facet_robust.png

FacetGrid Objects

xarray.plot.FacetGrid is used to control the behavior of themultiple plots.It borrows an API and code from Seaborn’s FacetGrid.The structure is contained within the axes and name_dictsattributes, both 2d Numpy object arrays.

  1. In [77]: g.axes
  2. Out[77]:
  3. array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f33f2dad358>,
  4. <matplotlib.axes._subplots.AxesSubplot object at 0x7f33f2d554a8>,
  5. <matplotlib.axes._subplots.AxesSubplot object at 0x7f33f2d7e438>],
  6. [<matplotlib.axes._subplots.AxesSubplot object at 0x7f33f2d2a3c8>,
  7. <matplotlib.axes._subplots.AxesSubplot object at 0x7f33f2cd3358>,
  8. <matplotlib.axes._subplots.AxesSubplot object at 0x7f33f2cff2e8>]], dtype=object)
  9.  
  10. In [78]: g.name_dicts
  11. Out[78]:
  12. array([[{'time': numpy.datetime64('2013-01-01T00:00:00.000000000')},
  13. {'time': numpy.datetime64('2013-03-04T12:00:00.000000000')},
  14. {'time': numpy.datetime64('2013-05-06T00:00:00.000000000')}],
  15. [{'time': numpy.datetime64('2013-07-07T12:00:00.000000000')},
  16. {'time': numpy.datetime64('2013-09-08T00:00:00.000000000')}, None]], dtype=object)

It’s possible to select the xarray.DataArray orxarray.Dataset corresponding to the FacetGrid through thename_dicts.

  1. In [79]: g.data.loc[g.name_dicts[0, 0]]
  2. Out[79]:
  3. <xarray.DataArray 'air' (lat: 25, lon: 53)>
  4. array([[-100. , -30.649994, -29.649994, ..., -40.350006, -37.649994,
  5. -34.550003],
  6. [ -29.350006, -28.649994, -28.449997, ..., -40.350006, -37.850006,
  7. -33.850006],
  8. [ -23.149994, -23.350006, -24.259995, ..., -39.949997, -36.759995,
  9. -31.449997],
  10. ...,
  11. [ 23.450012, 23.049988, 23.25 , ..., 22.25 , 21.950012,
  12. 21.549988],
  13. [ 22.75 , 23.049988, 23.640015, ..., 22.75 , 22.75 ,
  14. 22.049988],
  15. [ 23.140015, 23.640015, 23.950012, ..., 23.75 , 23.640015,
  16. 23.450012]], dtype=float32)
  17. Coordinates:
  18. * lat (lat) float64 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  19. * lon (lon) float64 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
  20. time datetime64[ns] 2013-01-01
  21. Attributes:
  22. long_name: 4xDaily Air temperature at sigma level 995
  23. units: deg C
  24. precision: 2
  25. GRIB_id: 11
  26. GRIB_name: TMP
  27. var_desc: Air temperature
  28. dataset: NMC Reanalysis
  29. level_desc: Surface
  30. statistic: Individual Obs
  31. parent_stat: Other
  32. actual_range: [185.16 322.1 ]

Here is an example of using the lower level API and then modifying the axes afterthey have been plotted.

  1. In [80]: g = t.plot.imshow('lon', 'lat', col='time', col_wrap=3, robust=True)
  2.  
  3. In [81]: for i, ax in enumerate(g.axes.flat):
  4. ....: ax.set_title('Air Temperature %d' % i)
  5. ....:
  6.  
  7. In [82]: bottomright = g.axes[-1, -1]
  8.  
  9. In [83]: bottomright.annotate('bottom right', (240, 40))
  10. Out[83]: Text(240, 40, 'bottom right')
  11.  
  12. In [84]: plt.draw()

_images/plot_facet_iterator.pngTODO: add an example of using the map method to plot dataset variables(e.g., with plt.quiver).

Maps

To follow this section you’ll need to have Cartopy installed and working.

This script will plot the air temperature on a map.

  1. In [85]: import cartopy.crs as ccrs
  2.  
  3. In [86]: air = xr.tutorial.open_dataset('air_temperature').air
  4.  
  5. In [87]: ax = plt.axes(projection=ccrs.Orthographic(-80, 35))
  6.  
  7. In [88]: air.isel(time=0).plot.contourf(ax=ax, transform=ccrs.PlateCarree());
  8.  
  9. In [89]: ax.set_global(); ax.coastlines();

_images/plotting_maps_cartopy.pngWhen faceting on maps, the projection can be transferred to the plotfunction using the subplot_kws keyword. The axes for the subplots createdby faceting are accessible in the object returned by plot:

  1. In [90]: p = air.isel(time=[0, 4]).plot(transform=ccrs.PlateCarree(), col='time',
  2. ....: subplot_kws={'projection': ccrs.Orthographic(-80, 35)})
  3. ....:
  4.  
  5. In [91]: for ax in p.axes.flat:
  6. ....: ax.coastlines()
  7. ....: ax.gridlines()
  8. ....:
  9.  
  10. In [92]: plt.draw();

_images/plotting_maps_cartopy_facetting.png

Details

Ways to Use

There are three ways to use the xarray plotting functionality:

  • Use plot as a convenience method for a DataArray.

  • Access a specific plotting method from the plot attribute of aDataArray.

  • Directly from the xarray plot submodule.

These are provided for user convenience; they all call the same code.

  1. In [93]: import xarray.plot as xplt
  2.  
  3. In [94]: da = xr.DataArray(range(5))
  4.  
  5. In [95]: fig, axes = plt.subplots(ncols=2, nrows=2)
  6.  
  7. In [96]: da.plot(ax=axes[0, 0])
  8. Out[96]: [<matplotlib.lines.Line2D at 0x7f34246854e0>]
  9.  
  10. In [97]: da.plot.line(ax=axes[0, 1])
  11. Out[97]: [<matplotlib.lines.Line2D at 0x7f33f2f1d0b8>]
  12.  
  13. In [98]: xplt.plot(da, ax=axes[1, 0])
  14. Out[98]: [<matplotlib.lines.Line2D at 0x7f3424685d68>]
  15.  
  16. In [99]: xplt.line(da, ax=axes[1, 1])
  17. Out[99]: [<matplotlib.lines.Line2D at 0x7f34257d9860>]
  18.  
  19. In [100]: plt.tight_layout()
  20.  
  21. In [101]: plt.draw()

_images/plotting_ways_to_use.pngHere the output is the same. Since the data is 1 dimensional the line plotwas used.

The convenience method xarray.DataArray.plot() dispatches to an appropriateplotting function based on the dimensions of the DataArray and whetherthe coordinates are sorted and uniformly spaced. This tabledescribes what gets plotted:

DimensionsPlotting function
1xarray.plot.line()
2xarray.plot.pcolormesh()
Anything elsexarray.plot.hist()

Coordinates

If you’d like to find out what’s really going on in the coordinate system,read on.

  1. In [102]: a0 = xr.DataArray(np.zeros((4, 3, 2)), dims=('y', 'x', 'z'),
  2. .....: name='temperature')
  3. .....:
  4.  
  5. In [103]: a0[0, 0, 0] = 1
  6.  
  7. In [104]: a = a0.isel(z=0)
  8.  
  9. In [105]: a
  10. Out[105]:
  11. <xarray.DataArray 'temperature' (y: 4, x: 3)>
  12. array([[1., 0., 0.],
  13. [0., 0., 0.],
  14. [0., 0., 0.],
  15. [0., 0., 0.]])
  16. Dimensions without coordinates: y, x

The plot will produce an image corresponding to the values of the array.Hence the top left pixel will be a different color than the others.Before reading on, you may want to look at the coordinates andthink carefully about what the limits, labels, and orientation foreach of the axes should be.

  1. In [106]: a.plot()
  2. Out[106]: <matplotlib.collections.QuadMesh at 0x7f33f29d9e48>

_images/plotting_example_2d_simple.pngIt may seem strange thatthe values on the y axis are decreasing with -0.5 on the top. This is becausethe pixels are centered over their coordinates, and theaxis labels and ranges correspond to the values of thecoordinates.

Multidimensional coordinates

See also: Working with Multidimensional Coordinates.

You can plot irregular grids defined by multidimensional coordinates withxarray, but you’ll have to tell the plot function to use these coordinatesinstead of the default ones:

  1. In [107]: lon, lat = np.meshgrid(np.linspace(-20, 20, 5), np.linspace(0, 30, 4))
  2.  
  3. In [108]: lon += lat/10
  4.  
  5. In [109]: lat += lon/10
  6.  
  7. In [110]: da = xr.DataArray(np.arange(20).reshape(4, 5), dims=['y', 'x'],
  8. .....: coords = {'lat': (('y', 'x'), lat),
  9. .....: 'lon': (('y', 'x'), lon)})
  10. .....:
  11.  
  12. In [111]: da.plot.pcolormesh('lon', 'lat');

_images/plotting_example_2d_irreg.pngNote that in this case, xarray still follows the pixel centered convention.This might be undesirable in some cases, for example when your data is definedon a polar projection (GH781). This is why the default is to not followthis convention when plotting on a map:

  1. In [112]: import cartopy.crs as ccrs
  2.  
  3. In [113]: ax = plt.subplot(projection=ccrs.PlateCarree());
  4.  
  5. In [114]: da.plot.pcolormesh('lon', 'lat', ax=ax);
  6.  
  7. In [115]: ax.scatter(lon, lat, transform=ccrs.PlateCarree());
  8.  
  9. In [116]: ax.coastlines(); ax.gridlines(draw_labels=True);

_images/plotting_example_2d_irreg_map.pngYou can however decide to infer the cell boundaries and use theinfer_intervals keyword:

  1. In [117]: ax = plt.subplot(projection=ccrs.PlateCarree());
  2.  
  3. In [118]: da.plot.pcolormesh('lon', 'lat', ax=ax, infer_intervals=True);
  4.  
  5. In [119]: ax.scatter(lon, lat, transform=ccrs.PlateCarree());
  6.  
  7. In [120]: ax.coastlines(); ax.gridlines(draw_labels=True);

_images/plotting_example_2d_irreg_map_infer.png

Note

The data model of xarray does not support datasets with cell boundariesyet. If you want to use these coordinates, you’ll have to make the plotsoutside the xarray framework.

One can also make line plots with multidimensional coordinates. In this case, hue must be a dimension name, not a coordinate name.

  1. In [121]: f, ax = plt.subplots(2, 1)
  2.  
  3. In [122]: da.plot.line(x='lon', hue='y', ax=ax[0]);
  4.  
  5. In [123]: da.plot.line(x='lon', hue='x', ax=ax[1]);

_images/plotting_example_2d_hue_xy.png