Making temperature-salinity diagrams called the T-S diagram with python and R programming

Hafez Ahmad
3 min readMay 10, 2020

--

In oceanography, temperature-salinity diagrams called the T-S diagram are used to identify water masses. Water masses can be classified based on their temperature-salinity characteristics, but density cannot be used for classification, because two water masses of different temperatures and salinities may have the same density. It was introduced by Helland-Hansen (1916). I am going to show you how to make the TS diagram in both python and R programming languages. In a T-S diagram, potential temperature (on the vertical axis) is plotted versus salinity (on the horizontal axis). I have a dataset containing surface temperature and surface salinity of 156 observations.

Here the Plotting Strategies:

1: load dataset [here, it is CSV file]

2: find the minimum and maximum values of temperature and salinity

3: calculate seawater density from temperature and salinity

4: generate density value for making contour lines

5: making contour and levels for T-S diagram

6: make scatter plot of temperature and salinity

7: make color bar according to density values

In python, I will use pandas, numpy, and matplotlib and gsw packages.

Note: 1: pandas is a fast, powerful, flexible, and easy to use open-source data analysis and manipulation tool, built on top of the Python programming language.

2: Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays.

3: matplotlib is basically plotting package and

4: gsw This Python implementation of the Thermodynamic Equation of Seawater 2010 (TEOS-10) is based primarily on numpy ufunc wrappers of the GSW-C implementation

Code:

# -*- coding: utf-8 -*-
“””
Created on Sun May 10 20:50:52 2020

@author: hafez
“””

import numpy as np
import pandas as pd
import gsw

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

data=pd.read_csv(‘tsdata2008_2020.csv’)

ts=data[[‘temperatureSurface’, ‘salinitySurface’]]

df=ts.sort_values(‘temperatureSurface’,ascending=True)

mint=np.min(df[‘temperatureSurface’])
maxt=np.max(df[‘temperatureSurface’])

mins=np.min(df[‘salinitySurface’])
maxs=np.max(df[‘salinitySurface’])

tempL=np.linspace(mint-1,maxt+1,156)

salL=np.linspace(mins-1,maxs+1,156)

Tg, Sg = np.meshgrid(tempL,salL)
sigma_theta = gsw.sigma0(Sg, Tg)
cnt = np.linspace(sigma_theta.min(), sigma_theta.max(),156)

fig,ax=plt.subplots(figsize=(10,10))
#fig.suptitle(‘programmer:Hafez Ahmad’, fontsize=14, fontweight=’bold’)
cs = ax.contour(Sg, Tg, sigma_theta, colors=’grey’, zorder=1)
cl=plt.clabel(cs,fontsize=10,inline=False,fmt=’%.1f’)

sc=plt.scatter(df[‘salinitySurface’],df[‘temperatureSurface’],c=cnt,s=10)

cb=plt.colorbar(sc)

ax.set_xlabel(‘Salinity ($‰$)’)

ax.set_ylabel(‘Temperature[$^\circ$C]’)
ax.set_title(‘General T-S (Temperature and salinity) Diagram’,fontsize=14, fontweight=’bold’)
ax.xaxis.set_major_locator(MaxNLocator(nbins=6))
ax.yaxis.set_major_locator(MaxNLocator(nbins=8))
ax.tick_params(direction=’out’)
cb.ax.tick_params(direction=’out’)
cb.set_label(‘Density[kg m$^{-3}$]’)
plt.tight_layout()
plt.savefig(‘ts_diagram.png’,format=’png’,dpi=900,transparent=False)
plt.show()

In R , I will use marelac, plot3D library.

Note:

1: marlace: The package contains among others: (1) chemical and physical constants and datasets, e.g. atomic weights, gas constants, the earth bathymetry; (2) conversion factors (e.g. gram to mol to liter, barometric units, temperature, salinity); (3) physical functions, e.g. to estimate concentrations of conservative substances, gas transfer and diffusion coefficients, the Coriolis force and gravity; (4) thermophysical properties of the seawater, as from the UNESCO polynomial or the more recent derivation based on a Gibbs function.

2: plot3d: it provides 2-D and 3-D data, including perspective plots, slice plots, surface plots, scatter plots, etc.

Code:

library(marelac)
library(plot3D)
data<- read.csv(‘tsdata2008_2020.csv’)

ts<-data[,3:4]

mint=min(ts[‘temperatureSurface’])
maxt=max(ts[‘temperatureSurface’])
mins=min(ts[‘salinitySurface’])
maxs=max(ts[‘salinitySurface’])

salC<-seq(from=mins,to=maxs,length.out = 156)
tempC<-seq(from=mint,to=maxt,length.out = 156)

sigma.c<-outer(salC,tempC,FUN = function(S,t)sw_dens(S = S, t = t)-1000)
sigma.c

png(file = ‘ts_diagram.png’,width = 15,res=500,pointsize = 12,bg=’white’)

jpeg(file=”ts_diagram.jpeg”)
par(mar=c(5,5,4,6))
contour2D(x=salC,y=tempC,z=sigma.c,lwd=2,main=’General T-S (Temperature and salinity) Diagram’,
col=’black’,xlab=expression(‘Sanlinity(‰)’),ylab=expression(‘Temperature(‘*~degree*C*’)’))
temp<-unlist(ts[‘temperatureSurface’],use.names = FALSE)
sal<-unlist(ts[‘salinitySurface’],use.names = FALSE)
sigma_theta<-sw_dens(S=sal,t=temp)-1000
scatter2D(sal,temp,colvar = sigma_theta,pch=16,cex=1.25,add=TRUE,
clim = range(sigma.c),colkey = FALSE)
colkey(clim = range(sigma.c),dist = 0.005,side=4,add=TRUE,
clab = expression(‘Density(kg m”^-3")’),col.clab = ‘black’,
side.clab = 4,line.clab = 2.5,length = 1,width = 0.8,
col.axis = ‘black’,col.ticks = ‘black’,cex.axis = 0.9)

dev.off()

I have attached python and R code in the GitHub repository. Please check it.

--

--

Hafez Ahmad

I am an Oceanographer. I am using Python, R, MATLAB, Julia, and ArcGIS for data analysis, data visualization, Machine learning, and Ocean/ climate modeling.