datafile = "~/CMEMS_INSTAC/INSITU_MED_NRT_OBSERVATIONS_013_035/history/mooring/IR_TS_MO_61198.nc"

"""
Explanation: Read variables and units
We assume the data file is present in the following directory:
End of explanation
"""


import os
datafile = os.path.expanduser(datafile)

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)

"""
Explanation: We use the os mudule to extend the ~.
End of explanation
"""


temperature_values = np.ma.masked_where(temperatureQC != 1, temperature_values)

"""
Explanation: We also mask the temperature values that have quality flag not equal to 1.
End of explanation
"""


fig = plt.figure()
plt.plot(time2, temperature_values)
plt.ylabel(temperature_units)

"""
Explanation: Basic plot
We create the most simple plot, without any additional option.
End of explanation
"""


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()

"""
Explanation: Main problems:
* The figure is not large enough.
* The labels are too small.
Improved plot
With some commands the previous plot can be improved:
* The figure size is increased
* The font size is set to 20 (pts)
* The year labels are rotated 45º
End of explanation
"""


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

"""
Explanation: Final version
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.
End of explanation
"""


temperature_units2 = '($^{\circ}$C)'

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()

"""
Explanation: The units for the temperature are also changed:
End of explanation
"""


