In [2]:
%matplotlib inline
import netCDF4
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import dates
import numpy as np
We assume the data file is present in the following directory:
In [6]:
datafile = "~/CMEMS_INSTAC/INSITU_MED_NRT_OBSERVATIONS_013_035/history/mooring/IR_TS_MO_61198.nc"
We use the os mudule to extend the ~.
In [7]:
import os
datafile = os.path.expanduser(datafile)
In [8]:
with netCDF4.Dataset(datafile, 'r') as ds:
time_values = ds.variables['TIME'][:]
temperature_values = ds.variables['TEMP'][:]
temperatureQC = ds.variables['TEMP_QC'][:]
time_units = ds.variables['TIME'].units
temperature_units = ds.variables['TEMP'].units
time2 = netCDF4.num2date(time_values, time_units)
We also mask the temperature values that have quality flag not equal to 1.
In [58]:
temperature_values = np.ma.masked_where(temperatureQC != 1, temperature_values)
We create the most simple plot, without any additional option.
In [59]:
fig = plt.figure()
plt.plot(time2, temperature_values)
plt.ylabel(temperature_units)
Out[59]:
Main problems:
With some commands the previous plot can be improved:
In [65]:
mpl.rcParams.update({'font.size': 20})
fig = plt.figure(figsize=(15, 8))
ax = fig.add_subplot(111)
plt.plot(time2, temperature_values, linewidth=0.5)
plt.ylabel(temperature_units)
plt.xlabel('Year')
fig.autofmt_xdate()
plt.grid()
We want to add a title containing the coordinates of the station. Longitude and latitude are both stored as vectors, but we will only keep the mean position to be included in the title.
LaTeX syntax can be used, as in this example, with the degree symbol.
In [68]:
with netCDF4.Dataset(datafile, 'r') as ds:
lon = ds.variables['LONGITUDE'][:]
lat = ds.variables['LATITUDE'][:]
figure_title = r'Temperature evolution at \n%s$^\circ$E, %s$^\circ$N' % (lon.mean(), lat.mean())
print figure_title
The units for the temperature are also changed:
In [71]:
temperature_units2 = '($^{\circ}$C)'
In [75]:
fig = plt.figure(figsize=(15, 8))
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(dates.YearLocator(base=2))
ax.xaxis.set_minor_locator(dates.YearLocator())
plt.plot(time2, temperature_values, linewidth=0.5)
plt.ylabel(temperature_units2, rotation=0., horizontalalignment='right')
plt.title(figure_title)
plt.xlabel('Year')
fig.autofmt_xdate()
plt.grid()