Skip to content

Commit

Permalink
[BUG] Fix plots (#116)
Browse files Browse the repository at this point in the history
* show plots

* fix plots in demo notebook
  • Loading branch information
callumrollo authored Nov 14, 2024
1 parent 0655147 commit 60b9352
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 22 deletions.
27 changes: 21 additions & 6 deletions glidertest/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ def plot_updown_bias(df: pd.DataFrame, ax: plt.Axes = None, xlabel='Temperature
with plt.style.context(glidertest_style_file):
if ax is None:
fig, ax = plt.subplots()
force_plot = True
else:
fig = plt.gcf()
force_plot = False

if not all(hasattr(df, attr) for attr in ['dc', 'depth']):
ax.text(0.5, 0.55, xlabel, va='center', ha='center', transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.5, edgecolor='none'))
Expand All @@ -53,6 +55,8 @@ def plot_updown_bias(df: pd.DataFrame, ax: plt.Axes = None, xlabel='Temperature
ax.set_ylim(df.depth.max() + 1, -df.depth.max() / 30)
ax.set_xlabel(xlabel)
ax.grid()
if force_plot:
plt.show()
return fig, ax

def plot_basic_vars(ds: xr.Dataset, v_res=1, start_prof=0, end_prof=-1):
Expand Down Expand Up @@ -150,7 +154,7 @@ def plot_basic_vars(ds: xr.Dataset, v_res=1, start_prof=0, end_prof=-1):
ax[1].text(0.3, 0.5, 'Oxygen data unavailable', va='top', transform=ax[1].transAxes)
[a.set_ylim(depthG.max() + 10, -5) for a in ax]
[a.grid() for a in ax]

plt.show()
return fig, ax


Expand Down Expand Up @@ -205,6 +209,7 @@ def process_optics_assess(ds, var='CHLA'):
ax.set(ylim=(np.nanpercentile(bottom_opt_data, 0.5), np.nanpercentile(bottom_opt_data, 99.5)),
xlabel='Measurements',
ylabel=var)
plt.show()
percentage_change = (((slope * len(bottom_opt_data) + intercept) - intercept) / abs(intercept)) * 100

if abs(percentage_change) >= 1:
Expand Down Expand Up @@ -247,8 +252,10 @@ def plot_daynight_avg(day: pd.DataFrame, night: pd.DataFrame, ax: plt.Axes = Non
with plt.style.context(glidertest_style_file):
if ax is None:
fig, ax = plt.subplots()
force_plot = True
else:
fig = plt.gcf()
force_plot = False
ax.plot(night.where(night.date == sel_day).dropna().dat, night.where(night.date == sel_day).dropna().depth,
label='Night time average')
ax.plot(day.where(day.date == sel_day).dropna().dat, day.where(day.date == sel_day).dropna().depth,
Expand All @@ -258,6 +265,8 @@ def plot_daynight_avg(day: pd.DataFrame, night: pd.DataFrame, ax: plt.Axes = Non
ax.grid()
ax.set(xlabel=xlabel, ylabel='Depth [m]')
ax.set_title(sel_day)
if force_plot:
plt.show()
return fig, ax


Expand Down Expand Up @@ -325,6 +334,7 @@ def plot_quench_assess(ds: xr.Dataset, sel_var: str, ax: plt.Axes = None, start_
ax.axvline(np.unique(m), c='orange')
ax.set_ylabel('Depth [m]')
plt.colorbar(c, label=f'{sel_var} [{ds[sel_var].units}]')
plt.show()
return fig, ax


Expand Down Expand Up @@ -356,7 +366,7 @@ def check_temporal_drift(ds: xr.Dataset, var: str, ax: plt.Axes = None, **kw: di
fig = plt.gcf()

ax[0].scatter(mdates.date2num(ds.TIME), ds[var], s=10)
#ax[0].xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax[0].xaxis.set_major_formatter(DateFormatter('%d-%b'))
ax[0].set(ylim=(np.nanpercentile(ds[var], 0.01), np.nanpercentile(ds[var], 99.99)), ylabel=var)

c = ax[1].scatter(ds[var], ds.DEPTH, c=mdates.date2num(ds.TIME), s=10)
Expand All @@ -365,6 +375,7 @@ def check_temporal_drift(ds: xr.Dataset, var: str, ax: plt.Axes = None, **kw: di

[a.grid() for a in ax]
plt.colorbar(c, format=DateFormatter('%b %d'))
plt.show()
return fig, ax


Expand Down Expand Up @@ -580,6 +591,7 @@ def plot_grid_spacing(ds: xr.Dataset, ax: plt.Axes = None, **kw: dict) -> tuple(
axes.tick_params(axis='both', which='major')
# More subtle grid lines
axes.grid(True, which='both', linestyle='--', linewidth=0.5, color='grey')
plt.show()

return fig, ax

Expand Down Expand Up @@ -659,7 +671,7 @@ def plot_ts(ds: xr.Dataset, ax: plt.Axes = None, **kw: dict) -> tuple({plt.Figur
cbar.set_label('Log Counts')
ax[2].set_xlabel('Absolute Salinity ( )')
ax[2].set_ylabel('Conservative Temperature (°C)')
ax[2].set_title('2D Histogram (Log Scale)')
ax[2].set_title('2D Histogram \n (Log Scale)')
# Set x-limits based on salinity plot and y-limits based on temperature plot
ax[2].set_xlim(ax[1].get_xlim())
ax[2].set_ylim(ax[0].get_xlim())
Expand All @@ -685,6 +697,7 @@ def plot_ts(ds: xr.Dataset, ax: plt.Axes = None, **kw: dict) -> tuple({plt.Figur
fig_width, fig_height = fig.get_size_inches()
new_height = box0.width * fig_width / fig_height
ax[2].set_position([box2.x0, box2.y0, box2.width, new_height])
plt.show()

return fig, ax

Expand Down Expand Up @@ -767,8 +780,9 @@ def plot_vertical_speeds_with_histograms(ds, start_prof=None, end_prof=None):
legend_loc = 'upper right'
else:
legend_loc = 'lower right'
plt.rcParams['legend.fontsize'] = 12
ax1_hist.legend(loc=legend_loc)

plt.rcParams['legend.fontsize'] = 15
# Lower left subplot for vertical water speed
ax2 = axs[1, 0]
ax2.axhline(0, color='gray', linestyle='-', linewidth=0.5) # Add zero horizontal line
Expand Down Expand Up @@ -896,6 +910,7 @@ def plot_combined_velocity_profiles(ds_out_dives: xr.Dataset, ds_out_climbs: xr.
plt.tight_layout()
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
ax.tick_params(axis='both', which='major')
return fig, ax
ax.legend()
plt.show()
return fig, ax
32 changes: 16 additions & 16 deletions notebooks/demo.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "8ca89b5a-37aa-43db-97a4-d25a8a140a30",
"id": "f4f1eb80-1e06-45ec-afbf-7b589d46779b",
"metadata": {},
"outputs": [],
"source": [
Expand Down Expand Up @@ -114,7 +114,7 @@
"# Plot about 20 profiles to see the behaviour of the flight model\n",
"start_prof = 400\n",
"end_prof = 420\n",
"plots.plot_vertical_speeds_with_histograms(ds_sg014, start_prof, end_prof)"
"plots.plot_vertical_speeds_with_histograms(ds_sg014, start_prof, end_prof);"
]
},
{
Expand Down Expand Up @@ -168,7 +168,7 @@
"outputs": [],
"source": [
"# Basic diagnostics of the gridding in the dataset\n",
"plots.plot_grid_spacing(ds)"
"plots.plot_grid_spacing(ds);"
]
},
{
Expand All @@ -179,7 +179,7 @@
"outputs": [],
"source": [
"# Basic diagnostics of the watermass properties\n",
"plots.plot_ts(ds)"
"plots.plot_ts(ds);"
]
},
{
Expand Down Expand Up @@ -221,7 +221,7 @@
"outputs": [],
"source": [
"tools.check_monotony(ds.PROFILE_NUMBER)\n",
"plots.plot_prof_monotony(ds)"
"plots.plot_prof_monotony(ds);"
]
},
{
Expand All @@ -240,14 +240,12 @@
"outputs": [],
"source": [
"fig, ax = plt.subplots(1, 4, figsize=(15, 5))\n",
"\n",
"plots.plot_updown_bias(tools.quant_updown_bias(ds, var='TEMP', v_res=1), ax[0], xlabel='Temperature [C]')\n",
"plots.plot_updown_bias(tools.quant_updown_bias(ds, var='PSAL', v_res=1), ax[1], xlabel='Salinity [PSU]')\n",
"plots.plot_updown_bias(tools.quant_updown_bias(ds, var='DOXY', v_res=1), ax[2], xlabel='Dissolved Oxygen [mmol m-3]')\n",
"plots.plot_updown_bias(tools.quant_updown_bias(ds, var='CHLA', v_res=1), ax[3], xlabel='Chlorophyll [mg m-3]')\n",
"\n",
"\n",
"ax[0].set_ylabel('Depth [m]')"
"ax[0].set_ylabel('Depth [m]')\n",
"plt.show()"
]
},
{
Expand Down Expand Up @@ -283,7 +281,7 @@
"metadata": {},
"outputs": [],
"source": [
"plots.process_optics_assess(ds, var='CHLA')"
"plots.process_optics_assess(ds, var='CHLA');"
]
},
{
Expand All @@ -306,7 +304,7 @@
"# Let's visually check a section of chlorphyll and see if we observe any NPQ\n",
"fig, ax = plt.subplots(1, 1, figsize=(15, 5))\n",
"\n",
"plots.plot_quench_assess(ds, 'CHLA', ax, ylim=35)"
"plots.plot_quench_assess(ds, 'CHLA', ax, ylim=35);"
]
},
{
Expand All @@ -333,7 +331,8 @@
"\n",
"plots.plot_daynight_avg( dayT, nightT, ax[0], xlabel='Temperature [C]')\n",
"plots.plot_daynight_avg( dayS, nightS, ax[1], xlabel='Salinity [PSU]')\n",
"plots.plot_daynight_avg( dayC, nightC, ax[2], xlabel='Chlorophyll [mg m-3]')"
"plots.plot_daynight_avg( dayC, nightC, ax[2], xlabel='Chlorophyll [mg m-3]')\n",
"plt.show()"
]
},
{
Expand Down Expand Up @@ -377,7 +376,8 @@
"outputs": [],
"source": [
"fig, ax = plt.subplots(1, 1, figsize=(5, 5))\n",
"plots.plot_updown_bias(tools.quant_updown_bias(ds, var='DPAR', v_res=1), ax, xlabel='Irradiance')"
"plots.plot_updown_bias(tools.quant_updown_bias(ds, var='DPAR', v_res=1), ax, xlabel='Irradiance')\n",
"plt.show()"
]
},
{
Expand Down Expand Up @@ -418,7 +418,7 @@
"metadata": {},
"outputs": [],
"source": [
"plots.process_optics_assess(ds, var='BBP700')"
"plots.process_optics_assess(ds, var='BBP700');"
]
},
{
Expand All @@ -440,7 +440,7 @@
"metadata": {},
"outputs": [],
"source": [
"plots.check_temporal_drift(ds, var='DOXY')"
"plots.check_temporal_drift(ds, var='DOXY');"
]
},
{
Expand Down Expand Up @@ -468,7 +468,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.8"
"version": "3.10.12"
}
},
"nbformat": 4,
Expand Down

0 comments on commit 60b9352

Please sign in to comment.