Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating new function plot_ts for TS diagram #125

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion gliderpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
__version__ = "unknown"

from .fetchers import GliderDataFetcher
from .plotting import plot_track, plot_transect
from .plotting import plot_track, plot_transect, plot_ctd, plot_ts

__all__ = [
"GliderDataFetcher",
"plot_track",
"plot_transect",
"plot_ts",
"plot_cast",
]
74 changes: 71 additions & 3 deletions gliderpy/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@

try:
import cartopy.crs as ccrs
import gsw
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator

except ModuleNotFoundError:
warnings.warn(
"gliderpy requires matplotlib and cartopy for plotting.",
Expand All @@ -24,7 +28,7 @@


@register_dataframe_method
def plot_track(df: pd.DataFrame) -> tuple(plt.Figure, plt.Axes):
def plot_track(df: pd.DataFrame) -> tuple[plt.Figure, plt.Axes]:
"""Plot a track of glider path coloured by temperature.

:return: figures, axes
Expand All @@ -49,7 +53,7 @@ def plot_transect(
var: str,
ax: plt.Axes = None,
**kw: dict,
) -> tuple(plt.Figure, plt.Axes):
) -> tuple[plt.Figure, plt.Axes]:
"""Make a scatter plot of depth vs time coloured by a user defined
variable.

Expand Down Expand Up @@ -99,7 +103,7 @@ def plot_cast(
var: str,
ax: plt.Axes = None,
color: str | None = None,
) -> tuple:
) -> tuple[plt.Figure, plt.Axes]:
"""Make a CTD profile plot of pressure vs property
depending on what variable was chosen.

Expand All @@ -123,3 +127,67 @@ def plot_cast(
ax.invert_yaxis()

return fig, ax


@register_dataframe_method
def plot_ts(
df: pd.DataFrame,
profile_number: int,
) -> tuple[plt.Figure, plt.Axes]:
"""Make a TS diagram from a chosen profile number.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should do the TS for the whole track. TS diagrams have many uses and the very first one is tp assess data quality, find oddities, etc. I believe that this function will be used to for quick data inspection like that, not really a final figure for a paper or refined research.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ocefpaf , to create a plot with all the profiles, I would need to interpolate them so that they are in the same pressure intervals, adding NaN where the profiles are shallower than others. Do my thoughts make sense, or is there a simpler way?


:param profile_number: profile number of CTD
:return: figure, axes
"""
g = df.groupby(["longitude", "latitude"])
profile = g.get_group(list(g.groups)[profile_number])

sa = gsw.conversions.SA_from_SP(
profile["salinity"],
profile["pressure"],
profile["longitude"].iloc[profile_number],
profile["latitude"].iloc[profile_number],
)

ct = gsw.conversions.CT_from_t(
sa,
profile["temperature"],
profile["pressure"],
)

min_temp, max_temp = np.min(ct), np.max(ct)
min_sal, max_sal = np.min(sa), np.max(sa)

num_points = len(profile["pressure"])
temp_grid = np.linspace(min_temp - 1, max_temp + 1, num_points)
sal_grid = np.linspace(min_sal - 1, max_sal + 1, num_points)

tg, sg = np.meshgrid(temp_grid, sal_grid)
sigma_theta = gsw.sigma0(sg, tg)

fig, ax = plt.subplots(figsize=(10, 10))

cs = ax.contour(sg, tg, sigma_theta, colors="grey", zorder=1)
plt.clabel(cs, fontsize=10, inline=False, fmt="%.1f")

sc = ax.scatter(
sa,
ct,
c=profile["pressure"],
cmap="plasma_r",
marker="o",
s=50,
)

cb = plt.colorbar(sc)
cb.ax.invert_yaxis()
cb.set_label("Pressure")

ax.set_xlabel("Salinity")
ax.set_ylabel("Temperature")
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")

return fig, ax
Binary file added gliderpy/tests/baseline/test_plot_ctd.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added gliderpy/tests/baseline/test_plot_track.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added gliderpy/tests/baseline/test_plot_transect.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added gliderpy/tests/baseline/test_plot_ts.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
erddapy
gsw
httpx
pandas
pandas-flavor
Expand Down
Binary file added tests/baseline/test_plot_ts.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 8 additions & 1 deletion tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import pytest

from gliderpy.fetchers import GliderDataFetcher
from gliderpy.plotting import plot_cast, plot_track, plot_transect
from gliderpy.plotting import plot_cast, plot_track, plot_transect, plot_ts

root = Path(__file__).parent

Expand Down Expand Up @@ -80,3 +80,10 @@ def test_plot_cast(glider_data):
"""Test plot_cast accessor."""
fig, ax = plot_cast(glider_data, 0, var="temperature", color="blue")
return fig


@pytest.mark.mpl_image_compare(baseline_dir=root.joinpath("baseline/"))
def test_plot_ts(glider_data):
"""Test plot_ts accessor."""
fig, ax = plot_ts(glider_data, 0)
return fig
Loading