Skip to content

Commit

Permalink
adjust notebooks
Browse files Browse the repository at this point in the history
  • Loading branch information
Zeitsperre committed Sep 3, 2024
1 parent c66cd4d commit c2fa9a2
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 45 deletions.
8 changes: 5 additions & 3 deletions docs/notebooks/figanos_colours.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,15 @@
"\n",
"from figanos import data\n",
"import figanos.matplotlib as fg\n",
"fg.utils.set_mpl_style('ouranos')\n",
"\n",
"import matplotlib as mpl\n",
"import numpy as np\n",
"import json\n",
"from matplotlib.patches import Rectangle\n",
"from pathlib import Path\n",
"from matplotlib import pyplot as plt"
"from matplotlib import pyplot as plt\n",
"\n",
"fg.utils.set_mpl_style('ouranos')\n"
]
},
{
Expand All @@ -54,8 +55,9 @@
"metadata": {},
"outputs": [],
"source": [
"with open(data() / \"ipcc_colors\" / \"variable_groups.json\") as f:\n",
"with data().joinpath(\"ipcc_colors\").joinpath(\"variable_groups.json\").open(encoding=\"utf-8\") as f:\n",
" var_dict = json.load(f)\n",
"\n",
"for f in sorted(data().joinpath(\"ipcc_colors/continuous_colormaps_rgb_0-255\").glob(\"*\")):\n",
" name=Path(f).name.replace('.txt','')\n",
" cmap = fg.utils.create_cmap(filename=name)\n",
Expand Down
58 changes: 29 additions & 29 deletions docs/notebooks/figanos_docs.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
"metadata": {},
"outputs": [],
"source": [
"from __future__ import annotations\n",
"\n",
"%load_ext autoreload\n",
"%autoreload 2\n",
"\n",
Expand Down Expand Up @@ -381,7 +383,7 @@
"metadata": {},
"outputs": [],
"source": [
"# Using 'median' as a key to make it the line label in the legend.\n",
"# Use 'median' as a key to make it the line label in the legend.\n",
"# legend='full' will create a legend entry for the shaded area\n",
"fg.plot.timeseries({'median': ds_time}, legend='full', show_lat_lon=False)"
]
Expand All @@ -401,7 +403,7 @@
"metadata": {},
"outputs": [],
"source": [
"#Create a Dataset with different names as to not trigger the shaded line plot\n",
"# Create a Dataset with different names as to not trigger the shaded line plot\n",
"ds_mod = ds_time.copy()\n",
"ds_mod = ds_mod.rename({'tx_max_p50': 'var1','tx_max_p10': 'var2','tx_max_p90': 'var3'})\n",
"\n",
Expand Down Expand Up @@ -432,7 +434,7 @@
"metadata": {},
"outputs": [],
"source": [
"#creating fake scenarios\n",
"# Create fake scenarios\n",
"data = {'tasmax_ssp434': ds_time,\n",
" 'tasmax_ssp245': ds_time.copy()-10,\n",
" 'tasmax_ssp585': ds_time.copy()+10}\n",
Expand Down Expand Up @@ -463,10 +465,10 @@
"metadata": {},
"outputs": [],
"source": [
"#Selecting a time and slicing our starting Dataset\n",
"# Select a time and slicing our starting Dataset\n",
"ds_space = opened[['tx_max_p50']].isel(time=0).sel(lat=slice(40,65), lon=slice(-90,-55))\n",
"\n",
"# defining our projection.\n",
"# Define our spatial projection.\n",
"projection = ccrs.LambertConformal()\n",
"\n",
"fg.gridmap(ds_space, projection = projection, features = ['coastline','ocean'], frame = True, show_time = 'lower left')"
Expand Down Expand Up @@ -510,11 +512,11 @@
"metadata": {},
"outputs": [],
"source": [
"#change the name of our DataArray for one that inclues 'pr' (precipitation) - this is still the same temperature data\n",
"# Change the name of our DataArray for one that includes 'pr' (precipitation) - this is still the same temperature data\n",
"da_pr = ds_space.tx_max_p50.copy()\n",
"da_pr.name = 'pr_max_p50'\n",
"\n",
"#diverging colormap with 8 levels, centered at 300\n",
"# Create a diverging colormap with 8 levels, centered at 300\n",
"ax = fg.gridmap(da_pr, projection=projection, divergent=300, levels=8, plot_kw={'cbar_kwargs':{'label':'precipitation'}})\n",
"ax.set_title('This is still temperature data,\\nbut let\\'s pretend.')"
]
Expand All @@ -534,7 +536,7 @@
"metadata": {},
"outputs": [],
"source": [
"#creating the same map, with 'nice' levels.\n",
"# Create the same map, with 'nice' levels.\n",
"ax = fg.gridmap(da_pr, projection=projection, divergent=300,\n",
" plot_kw={'levels':8, 'cbar_kwargs':{'label':None}}, show_time=(0.85, 0.8))\n",
"ax.set_title('This cmap has 6 levels instead of 8,\\nbut aren\\'t they nice?')"
Expand Down Expand Up @@ -567,7 +569,7 @@
"metadata": {},
"outputs": [],
"source": [
"#Creating custom cmap (refer to https://matplotlib.org/stable/tutorials/colors/colormap-manipulation.html#directly-creating-a-segmented-colormap-from-a-list)\n",
"# Create a custom colour map (refer to https://matplotlib.org/stable/tutorials/colors/colormap-manipulation.html#directly-creating-a-segmented-colormap-from-a-list)\n",
"from matplotlib.colors import LinearSegmentedColormap\n",
"custom_colors =[\"darkorange\", \"gold\", \"lawngreen\", \"lightseagreen\"]\n",
"custom_cmap = LinearSegmentedColormap.from_list(\"mycmap\", custom_colors)\n",
Expand Down Expand Up @@ -623,7 +625,7 @@
"metadata": {},
"outputs": [],
"source": [
"# create a fictional observational dataset from scratch\n",
"# Create a fictional observational dataset from scratch\n",
"names = ['station_' + str(i) for i in np.arange(10)]\n",
"lat = 45 + np.random.rand(10)*3\n",
"lon = np.linspace(-76,-70, 10)\n",
Expand All @@ -647,14 +649,14 @@
"tas = tas.to_dataset()\n",
"tas.attrs[\"description\"] = \"Observations\"\n",
"\n",
"#set nice features\n",
"# Set nice features\n",
"features = {\"land\": {\"color\": \"#f0f0f0\"},\n",
" \"rivers\": {\"edgecolor\": \"#cfd3d4\"},\n",
" \"lakes\": {\"facecolor\": \"#cfd3d4\"},\n",
" \"coastline\": {\"edgecolor\": \"black\"},\n",
"}\n",
"\n",
"# plot\n",
"# Plot\n",
"ax =fg.scattermap(tas,\n",
" transform=ccrs.PlateCarree(),\n",
" sizes ='years',\n",
Expand Down Expand Up @@ -731,6 +733,7 @@
"outputs": [],
"source": [
"from xclim import ensembles\n",
"\n",
"urls = ['https://pavics.ouranos.ca/twitcher/ows/proxy/thredds/dodsC/birdhouse/ouranos/portraits-clim-1.1/NorESM1-M_rcp85_prcptot_monthly.nc',\n",
" 'https://pavics.ouranos.ca/twitcher/ows/proxy/thredds/dodsC/birdhouse/ouranos/portraits-clim-1.1/MPI-ESM-LR_rcp85_prcptot_monthly.nc',\n",
" 'https://pavics.ouranos.ca/twitcher/ows/proxy/thredds/dodsC/birdhouse/ouranos/portraits-clim-1.1/IPSL-CM5B-LR_rcp85_prcptot_monthly.nc',\n",
Expand Down Expand Up @@ -835,7 +838,7 @@
"metadata": {},
"outputs": [],
"source": [
"# create two datasets of mean annual temperature relative to the 1981-2010 period\n",
"# Create two datasets of mean annual temperature relative to the 1981-2010 period\n",
"url1 = 'https://pavics.ouranos.ca/twitcher/ows/proxy/thredds/dodsC/birdhouse/ouranos/portraits-clim-1.3/MPI-ESM-LR_rcp85_tx_mean_annual.nc'\n",
"rcp85 = xr.open_dataset(url1, decode_timedelta=False)\n",
"rcp85 = rcp85.sel(lon=-73, lat=46, method='nearest')\n",
Expand All @@ -850,7 +853,7 @@
"rcp45_deltas.tx_mean_annual.attrs['long_name'] = 'Annual mean of daily max temp relative to 1981-2010'\n",
"rcp45_deltas.tx_mean_annual.attrs['units'] = 'K'\n",
"\n",
"# plot\n",
"# Plot\n",
"fg.stripes({'rcp45': rcp45_deltas, 'rcp85': rcp85_deltas}, divide=2006)"
]
},
Expand All @@ -869,7 +872,7 @@
"metadata": {},
"outputs": [],
"source": [
"# creating a similar dataset with precipitation data\n",
"# Create a similar dataset with precipitation data\n",
"url3 = 'https://pavics.ouranos.ca/twitcher/ows/proxy/thredds/dodsC/birdhouse/ouranos/portraits-clim-1.3/MPI-ESM-LR_rcp85_precip_accumulation_annual.nc'\n",
"prec = xr.open_dataset(url3, decode_timedelta=False)\n",
"prec = prec.sel(lon=-73, lat=46, method='nearest')\n",
Expand Down Expand Up @@ -940,8 +943,7 @@
"metadata": {},
"outputs": [],
"source": [
"# create diagnostics Dataset from scratch\n",
"\n",
"# Create a diagnostics Dataset from scratch\n",
"improvement = np.random.rand(7,7)\n",
"diagnostics = xr.DataArray(data=improvement,\n",
" coords=dict(realization=['model1', 'model2', 'model3', 'model4', 'model5', 'model6', 'model7'],\n",
Expand All @@ -950,8 +952,7 @@
"\n",
"diagnostics.attrs['long_name'] = \"% of improved grid cells\"\n",
"\n",
"# plot heatmap\n",
"\n",
"# Plot a heatmap\n",
"fg.heatmap(diagnostics, divergent=0.5, plot_kw={'vmin': 0, 'linecolor': 'w', 'linewidth':1.5})\n"
]
},
Expand All @@ -978,7 +979,9 @@
" divergent=0.5,\n",
" plot_kw={'cbar_kws':{'label': 'Proportion of cells improved'}, 'annot':True}\n",
" )\n",
"ax.set_xlabel(\"\") # get rid of labels\n",
"\n",
"# Remove the grid labels\n",
"ax.set_xlabel(\"\")\n",
"ax.set_ylabel(\"\")"
]
},
Expand Down Expand Up @@ -1039,8 +1042,8 @@
"source": [
"from xclim.testing import open_dataset\n",
"\n",
"ds_ref = open_dataset(\"sdba/ahccd_1950-2013.nc\")\n",
"ds_sim = open_dataset(\"sdba/nrcan_1950-2013.nc\")\n",
"ds_ref = open_dataset(\"sdba/ahccd_1950-2013.nc\", branch=\"v2023.12.14\")\n",
"ds_sim = open_dataset(\"sdba/nrcan_1950-2013.nc\", branch=\"v2023.12.14\")\n",
"for v in ds_ref.data_vars: \n",
" ds_sim[v] = xc.core.units.convert_units_to(ds_sim[v], ds_ref[v], context=\"hydro\")\n",
"\n",
Expand Down Expand Up @@ -1092,8 +1095,6 @@
"outputs": [],
"source": [
"# Fetch data\n",
"from __future__ import annotations\n",
"\n",
"import pandas as pd\n",
"\n",
"import xclim.ensembles\n",
Expand Down Expand Up @@ -1156,18 +1157,17 @@
"\n",
"#FIXME: xc.ensembles.fractional_uncertainty has not been released yet. Until until it is released, here it is.\n",
"def fractional_uncertainty(u: xr.DataArray):\n",
" \"\"\"\n",
" Return the fractional uncertainty.\n",
" \"\"\"Return the fractional uncertainty.\n",
"\n",
" Parameters\n",
" ----------\n",
" u: xr.DataArray\n",
" Array with uncertainty components along the `uncertainty` dimension.\n",
" u : xr.DataArray\n",
" Array with uncertainty components along the `uncertainty` dimension.\n",
"\n",
" Returns\n",
" -------\n",
" xr.DataArray\n",
" Fractional, or relative uncertainty with respect to the total uncertainty.\n",
" Fractional, or relative uncertainty with respect to the total uncertainty.\n",
" \"\"\"\n",
" uncertainty = u / u.sel(uncertainty=\"total\") * 100\n",
" uncertainty.attrs.update(u.attrs)\n",
Expand Down
26 changes: 13 additions & 13 deletions docs/notebooks/figanos_multiplots.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"metadata": {},
"outputs": [],
"source": [
"# create xarray object from a NetCDF\n",
"# Create a xarray object from a NetCDF\n",
"url = 'https://pavics.ouranos.ca//twitcher/ows/proxy/thredds/dodsC/birdhouse/disk2/cccs_portal/indices/Final/BCCAQv2_CMIP6/tx_max/YS/ssp585/ensemble_percentiles/tx_max_ann_BCCAQ2v2+ANUSPLIN300_historical+ssp585_1950-2100_30ymean_percentiles.nc'\n",
"opened = xr.open_dataset(url, decode_timedelta=False)"
]
Expand All @@ -74,7 +74,7 @@
"metadata": {},
"outputs": [],
"source": [
"#creating fake scenarios\n",
"# Create fake scenarios\n",
"ds_time = ds_time[['tx_max_p10', 'tx_max_p50', 'tx_max_p90']]\n",
"data = {'tasmax_ssp434': ds_time,\n",
" 'tasmax_ssp245': ds_time.copy()-10,\n",
Expand Down Expand Up @@ -103,10 +103,10 @@
"metadata": {},
"outputs": [],
"source": [
"#Selecting a time and slicing our starting Dataset\n",
"# Select a time and slicing our starting Dataset\n",
"ds_space = opened[['tx_max_p50']].isel(time=[0, 1, 2]).sel(lat=slice(40,65), lon=slice(-90,-55))\n",
"\n",
"# defining our projection.\n",
"# Defining a spatial projection\n",
"projection = ccrs.LambertConformal()\n",
"\n",
"im = fg.gridmap(ds_space,\n",
Expand Down Expand Up @@ -175,7 +175,6 @@
"metadata": {},
"outputs": [],
"source": [
"from xclim import ensembles\n",
"sup_305k = ds_space.where(ds_space.tx_max_p50>305)\n",
"inf_300k = ds_space.where(ds_space.tx_max_p50<300)\n",
"\n",
Expand Down Expand Up @@ -220,7 +219,7 @@
"source": [
"ds_space = opened[['tx_max_p50']].isel(time=[0, 1, 2]).sel(lat=slice(40,65), lon=slice(-90,-55))\n",
"\n",
"# spatial subbomain\n",
"# Select a spatial subdomain\n",
"sl = slice(100,100+5)\n",
"da = ds_space.isel(lat=sl, lon=sl).drop(\"horizon\").tx_max_p50\n",
"da[\"lon\"] = np.round(da.lon,2)\n",
Expand Down Expand Up @@ -274,16 +273,16 @@
"metadata": {},
"outputs": [],
"source": [
"vmin=280\n",
"vmax=310\n",
"V_MIN=280\n",
"V_MAX=310\n",
"ds_space = opened[['tx_max_p50']].isel(time=[0, 1, 2]).sel(lat=slice(40,65), lon=slice(-90,-55))\n",
"\n",
"im = fg.gridmap(ds_space,\n",
" projection = projection,\n",
" plot_kw = {\"col\": \"time\",\n",
" \"xlim\": (-77,-69),\n",
" \"ylim\": (43,50),\n",
" \"vmin\": vmin, \"vmax\": vmax,\n",
" \"vmin\": V_MIN, \"vmax\": V_MAX,\n",
" },\n",
" features = ['coastline','ocean'],\n",
" frame = False,\n",
Expand All @@ -294,8 +293,8 @@
" transform=ccrs.PlateCarree(),\n",
" plot_kw={'x':'lon',\n",
" 'y':'lat',\n",
" 'vmin': vmin,\n",
" 'vmax': vmax,\n",
" 'vmin': V_MIN,\n",
" 'vmax': V_MAX,\n",
" 'edgecolor':'grey',\n",
" 'add_colorbar': False},\n",
" show_time=False,\n",
Expand All @@ -317,7 +316,7 @@
"metadata": {},
"outputs": [],
"source": [
"#Selecting a time and slicing our starting Dataset\n",
"# Select a time and slicing for our starting Dataset\n",
"ds_space = opened[['tx_max_p50']].isel(time=[0, 1, 2]).sel(lat=slice(40,65), lon=slice(-90,-55))\n",
"\n",
"im = fg.gridmap(ds_space,\n",
Expand Down Expand Up @@ -353,6 +352,7 @@
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"op = opened.isel(time=[0, 1])\n",
"data = xr.DataArray(\n",
" data=np.array([op.tx_max_p10.values, op.tx_max_p50.values, op.tx_max_p90.values]),\n",
Expand All @@ -372,7 +372,7 @@
" fig_kw = {\"figsize\": (8, 7)},\n",
" )\n",
"\n",
"# modify xlabels positions (hardcoded in xarray.plot)\n",
"# Modify x-label positions (hardcoded in xarray.plot)\n",
"for i, fax in enumerate(im.axs.flat):\n",
" for txt in fax.texts:\n",
" if len(txt.get_text()) > 0:\n",
Expand Down

0 comments on commit c2fa9a2

Please sign in to comment.