#!/usr/bin/env python # coding: utf-8 # # Simple `hvplot` demo on ocean model data # [hvplot](https://hvplot.pyviz.org) is a high-level plotting API for pandas, dask, streamz and xarray built on HoloViews. I learned about it in [James Bednar's pyviz talk at SciPy 2018](https://www.youtube.com/watch?v=DGLi-UWReM8) and I've been using it since. It's a young project, but super useful. # # The great thing is you can just replace `.plot()` with `.hvplot()` on `xarray` and `pandas` objects and get interactive plots in your browser. # # It can be installed from the conda-forge channel: `conda install -c conda-forge hvplot` # In[1]: import xarray as xr # Let's open some global wave forecast data using an OPeNDAP link from Unidata's THREDDS server # In[2]: url = 'http://thredds.ucar.edu/thredds/dodsC/grib/FNMOC/WW3/Global_1p0deg/Best' # In[3]: ds = xr.open_dataset(url) # In[4]: ds # Let's look at significant wave height # In[5]: var = 'sig_wav_ht_surface' # In[6]: ds[var] # For this dataset, the time dimension is sometimes `time`, sometimes `time1` or `time2`, so determine it here: # In[7]: ds[var].dims # In[8]: time_dim = ds[var].dims[0] # `hvplot` currently has a known issue that is gets confused by extra time variables, so drop the associated `reftime` variable: # In[9]: ds = ds.drop('ref'+time_dim) # Now we are ready to try `hvplot`: # In[10]: import hvplot.xarray # We tell `hvplot` to group on time so that the time dimension appears on a slider (otherwise we get a histogram of all data): # In[11]: ds[var].hvplot(groupby=time_dim) # We can customize the plot via additional parameters, and because there is not yet a way to set the aspect ratio, set the size and width by eye to get a better aspect ratio: # In[12]: ds[var].hvplot(groupby=time_dim, clim=(0,5), label=var, rasterize=True, width=700, height=400, cmap='viridis') # Now let's extract a time series at a specified location # using xarray's selection by coordinate variable: # In[13]: lon = 302.5 lat = 25.23 label = f'{var} at lon: {lon}, lat: {lat}' d1d = ds[var].sel(lon=lon, lat=lat, method='nearest') # In[14]: type(d1d) # Using `hvplot` on this 1D `DataArray` does the right thing: # In[15]: d1d.hvplot() # Note that `hvplot` also works with `pandas`: # In[16]: import hvplot.pandas # In[17]: df = d1d.to_pandas() # In[18]: df.hvplot()