Calculate custom index: number of days with freezing mean temperature#
Example notebook that runs icclim.
The example calculates the number of days when the minimum temperature is freezing or below for the dataset chosen by the user on C4I. It uses the custom user index functionality of icclim.
We assume to have the tas variable in netCDF files in a ./data/latest folder. The data can be downloaded using the metalink provided with this notebook. The data described in a .metalink file can be downloaded with tools such as aria2 or a browser plugin such as DownThemAll! If you wish to use a different dataset, you can use the climate 4 impact
portal to search and select the data you wish to use and a metalink file to the ESGF data will be provided.
The data is read using xarray and a plot of the time series over a specific region is generated, as well as an average spatial map. Several output types examples are shown.
The dataset expected for this notebook is the tas variable for one climate model, one experiment and one member. The time period should be continuous.
To keep this example fast to run, the following period is considered: 2015-01-01 to 2019-12-31, and plots are shown over European region.
Packages Installation#
[ ]:
[ ]:
Specification of parameters#
[ ]:
# studied period
dt1 = datetime.datetime(2015, 1, 1, tzinfo=datetime.timezone.utc)
dt2 = datetime.datetime(2019, 12, 31, tzinfo=datetime.timezone.utc)
out_f = "ndays_tas_below_freezing_icclim.nc"
data_dir = Path("data/latest")
filenames = [str(f) for f in data_dir.glob("tas_day_GFDL-ESM4*.nc")]
filenames
[ ]:
[ ]:
icclim.index(
index_name=GenericIndicatorRegistry.CountOccurrences,
in_files=filenames,
threshold="< 0 deg_C",
var_name="tas",
slice_mode="year",
time_range=[dt1, dt2],
out_file=out_f,
logs_verbosity="HIGH",
)
Plot setup#
[ ]:
with xr.open_dataset(out_f, decode_times=False) as ds:
nf_xr = ds
ds["time"] = xr.decode_cf(ds).time
# Select a single x,y combination from the data
longitude = nf_xr["count_occurrences"]["lon"].sel(lon=3.5, method="nearest")
latitude = nf_xr["count_occurrences"]["lat"].sel(lat=44.2, method="nearest")
Subset and plot count_occurrences#
[ ]:
# Slice the data spatially using a single lat/lon point
one_point = nf_xr["count_occurrences"].sel(lat=latitude, lon=longitude)
# Use xarray to create a quick time series plot
one_point.plot.line()
plt.show()
[ ]:
# You can clean up your plot as you wish using standard matplotlib approaches
f, ax = plt.subplots(figsize=(12, 6))
one_point.plot.line(
hue="lat",
marker="o",
ax=ax,
color="grey",
markerfacecolor="purple",
markeredgecolor="purple",
)
ax.set(title="Time Series For a Single Lat / Lon Location")
plt.show()
[ ]:
# Convert to dataframe -- then this can easily be exported to a csv
one_point_df = one_point.to_dataframe()
# View just the first 5 rows of the data
one_point_df.head()
# Export data to .csv file
[ ]:
# Time subsetting: this is just an example on how to do it
start_date = "2018-01-01"
end_date = "2019-12-31"
nf = nf_xr["count_occurrences"].sel(time=slice(start_date, end_date))
[ ]:
# Quickly plot the data using xarray.plot()
nf.plot(x="lon", y="lat", col="time", col_wrap=1)
plt.suptitle("Two Time Steps of Number of freezing days", y=1.03)
plt.show()
[ ]:
# Set spatial extent and centre
central_lat = 47.0
central_lon = 1.0
extent = [-30, 30, 30, 56] # Western Europe
# Calculate time average
nf_avg = nf.mean(dim="time", keep_attrs=True)
# Set plot projection
map_proj = ccrs.AlbersEqualArea(
central_longitude=central_lon, central_latitude=central_lat
)
# Define plot
f, ax = plt.subplots(figsize=(14, 6), subplot_kw={"projection": map_proj})
# Plot data with proper colormap scale range
levels = np.arange(0, 90, 5)
p = nf_avg.plot(levels=levels, cmap="RdBu_r", transform=ccrs.PlateCarree())
# Plot information
plt.suptitle("Two Time Steps of Europe number of freezing days", y=1)
# Add the coastlines to axis and set extent
ax.coastlines()
ax.gridlines()
ax.set_extent(extent)
# Save plot as png
plt.savefig("c4i_nf_icclim.png")
[ ]:
# Re-order longitude so that there is no blank line at 0 deg because 0 deg is within our spatial selection
nf_avg.coords["lon"] = (nf_avg.coords["lon"] + 180) % 360 - 180
nf_avg = nf_avg.sortby(nf_avg.lon)
# Define plot
f, ax = plt.subplots(figsize=(14, 6), subplot_kw={"projection": map_proj})
# Define colorscale
levels = np.arange(0, 90, 15)
# Contours lines
p = nf_avg.plot.contour(
levels=levels, colors="k", linewidths=0.5, transform=ccrs.PlateCarree()
)
# Contour filled colors
p = nf_avg.plot.contourf(
levels=levels, cmap="RdBu_r", extend="both", transform=ccrs.PlateCarree()
)
# Plot information
plt.suptitle("Two Time Steps of Europe number of freezing days", y=1)
# Add the coastlines to axis and set extent
ax.coastlines()
ax.gridlines()
ax.set_extent(extent)
# Save plot as png
plt.savefig("c4i_nf_contours_icclim.png")