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

[WIP] plot_colorbar soft deprecation #1173

Draft
wants to merge 26 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
69ad6ea
soft deprecate plot_colorbar
ddkohler Mar 22, 2024
0b3f566
Merge branch 'master' into plan-plot_colorbar-deprecation
ddkohler Mar 22, 2024
daa1e46
Update CHANGELOG.md
ddkohler Mar 22, 2024
5c9eaa0
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 22, 2024
8122951
fix 2 warnings
ddkohler Mar 22, 2024
7ab3ab7
test build
ddkohler Mar 23, 2024
1509e85
Update fringes_transform.py
ddkohler Mar 23, 2024
8242466
test node20
ddkohler Mar 23, 2024
1834767
Update fringes_transform.py
ddkohler Mar 23, 2024
13386fd
try more for sphinx
ddkohler Mar 23, 2024
06e32b7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 23, 2024
31fa0bd
Update split.py
ddkohler Mar 23, 2024
fdf358c
re-implement module reset (#1175)
ddkohler Mar 24, 2024
ddf2db8
new example for norms, cbar
ddkohler Mar 31, 2024
c75a0d6
Merge branch 'master' into plan-plot_colorbar-deprecation
ddkohler Mar 31, 2024
39c36bf
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 31, 2024
1622cd9
abandon using datasets as module
ddkohler Mar 31, 2024
5cd0cf5
try new load method
ddkohler Apr 1, 2024
0be6b2e
datasets us SimpleNamespace
ddkohler Apr 1, 2024
6dc130e
Merge branch 'master' into plan-plot_colorbar-deprecation
ddkohler Apr 1, 2024
813228a
Update norms.py
ddkohler Apr 1, 2024
274f789
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Apr 1, 2024
35fc3a2
codeql
ddkohler Apr 1, 2024
6b4832d
Merge branch 'master' into plan-plot_colorbar-deprecation
ddkohler Apr 29, 2024
fa536ed
axis_label_from_data, deprecation warnings
ddkohler May 3, 2024
537c93f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] May 3, 2024
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/).
- refactor of artists.quick1D and artists.quick2D
- quick2D and quick1D will not force `autosave=True` if the number of figures is large. Instead, interactive plotting will be truncated if the number of figures is large.
- artists now gets turbo colormap straight from matplotlib
- deprecating `artists.plot_colorbar`: instead use matplotlib's `colorbar` implementations directly
- artists.interact2D now returns a `types.SimpleNamespace` object (rather than a tuple)

## [3.5.2]
Expand Down
3 changes: 2 additions & 1 deletion WrightTools/artists/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ def _parse_plot_args(self, *args, **kwargs):
data=data, channel_index=channel_index, dynamic_range=dynamic_range, **kwargs
)
if plot_type == "contourf":
if "levels" not in kwargs.keys():
if ("levels" not in kwargs.keys()) and ("norm" not in kwargs):
# because of _parse_limits, we ensur we always have vmin and vmax to use
kwargs["levels"] = np.linspace(kwargs["vmin"], kwargs["vmax"], 256)
elif plot_type == "contour":
if "levels" not in kwargs.keys():
Expand Down
70 changes: 56 additions & 14 deletions WrightTools/artists/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,19 @@

__all__ = [
"_title",
"axis_label_from_data",
"add_sideplot",
"corner_text",
"create_figure",
"diagonal_line",
"get_scaled_bounds",
"norm_from_channel",
"pcolor_helper",
"plot_colorbar",
"pcolor_helper", # deprecation imminent
"plot_colorbar", # to be deprecated (use mpl methods)
"plot_margins",
"plot_gridlines",
"plot_gridlines", # to be deprecated (use mpl methods, styles)
"savefig",
"set_ax_labels",
"set_ax_labels", # to be deprecated (use mpl methods, styles)
"set_ax_spines",
"set_fig_labels",
"subplots_adjust",
Expand All @@ -53,6 +54,34 @@
# --- functions -----------------------------------------------------------------------------------


def axis_label_from_data(data, ax=None, cax=None, which="both", channel_index=0):
"""Apply x and/or y labels to axes.
Parameters
----------
data : WrightTools.Data
data from which to extract the label(s)
ax : Axis object (optional)
Default is current axis
autolabel : {'none', 'both', 'x', 'y'} (optional)
Label(s) to apply from data. Default is none.
channel_index : integer (optional)
Channel index. Default is 0. Only important for 2D data
"""
if ax is None:
ax = plt.gca()
if which in ["both", "x"]:
xlabel = data.axes[0].label
ax.set_xlabel(xlabel)
if which in ["both", "y"]:
if data.ndim == 1:
ylabel = data.channels[channel_index].label
elif data.ndim == 2:
ylabel = data.axes[1].label
else:
raise wt_exceptions.DimensionalityError("<=3", data.ndim)
ax.set_ylabel(ylabel)


def _title(fig, title, subtitle="", *, margin=1, fontsize=20, subfontsize=18):
"""Add a title to a figure.

Expand Down Expand Up @@ -657,6 +686,11 @@ def plot_colorbar(
matplotlib.colorbar.ColorbarBase object
The created colorbar.
"""
warnings.warn(
"`plot_colorbar` is planned for deprecation. "
+ "Use `matplotlib.pyplot.colorbar` instead.",
wt_exceptions.VisibleDeprecationWarning,
)
# parse cax
if cax is None:
cax = plt.gca()
Expand Down Expand Up @@ -807,6 +841,12 @@ def plot_gridlines(ax=None, c="grey", lw=1, diagonal=False, zorder=2, makegrid=T
zorder : number (optional)
zorder of plotted grid. Default is 2.
"""
warnings.warn(
"``plot_gridlines`` is deprecated and will be removed in a future version. "
+ "Use matplotlib's ``grid`` methods instead",
wt_exceptions.VisibleDeprecationWarning,
)

# get ax
if ax is None:
ax = plt.gca()
Expand Down Expand Up @@ -913,6 +953,11 @@ def set_ax_labels(ax=None, xlabel=None, ylabel=None, xticks=None, yticks=None, l
--------
set_fig_labels
"""
warnings.warn(
"``set_ax_labels`` is deprecated and will be removed in a future version. "
+ "Use matplotlib's ``set_xlabel`` and ``set_ylabel`` methods instead",
wt_exceptions.VisibleDeprecationWarning,
)
# get ax
if ax is None:
ax = plt.gca()
Expand Down Expand Up @@ -1024,14 +1069,8 @@ def set_fig_labels(
for ax in fig.axes:
if ax.is_sideplot:
continue
try:
# [row|col]span were introduced in matplotlib 3.2
# this try/except can be removed when supprot for mpl < 3.2 is dropped
rowNum = ax.get_subplotspec().rowspan.start
colNum = ax.get_subplotspec().colspan.start
except AttributeError:
rowNum = ax.rowNum
colNum = ax.colNum
rowNum = ax.get_subplotspec().rowspan.start
colNum = ax.get_subplotspec().colspan.start
if row_start <= rowNum <= row_stop and col_start <= colNum <= col_stop:
if colNum == col_start:
set_ax_labels(ax=ax, ylabel=ylabel, yticks=yticks, label_fontsize=label_fontsize)
Expand All @@ -1047,8 +1086,11 @@ def set_fig_labels(


def subplots_adjust(fig=None, inches=1):
"""Enforce margins for generated figure, starting at subplots.
.. note::
"""
Enforce margins for generated figure, starting at subplots.

Note
----
You probably should be using wt.artists.create_figure instead.

Parameters
Expand Down
4 changes: 3 additions & 1 deletion WrightTools/artists/_interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,9 @@ def interact2D(
# colorbar
ticks = current_state.norm.ticks
ticklabels = gen_ticklabels(ticks, channel.signed)
colorbar = plot_colorbar(cax, cmap=cmap, label=channel.natural_name, ticks=ticks)
colorbar = fig.colorbar(
mappable=obj2D, cax=cax, cmap=cmap, label=channel.natural_name, ticks=ticks
)
colorbar.set_ticklabels(ticklabels)
fig.canvas.draw_idle()

Expand Down
3 changes: 2 additions & 1 deletion WrightTools/data/_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
def join(
datas, *, atol=None, rtol=None, name="join", parent=None, method="first", verbose=True
) -> Data:
"""Join a list of data objects into one data object.
"""
Join a list of data objects into one data object.
The underlying dataset arrays are merged.

Joined datas must have the same axes and axes order.
Expand Down
84 changes: 46 additions & 38 deletions WrightTools/datasets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@


import pathlib
from types import SimpleNamespace

from .. import kit as wt_kit

Expand All @@ -17,8 +18,27 @@
# --- container class -----------------------------------------------------------------------------


class DatasetContainer(object):
def _from_files(self, dirname, prefix=""):
BrunoldrRaman = SimpleNamespace()
Cary = SimpleNamespace()
COLORS = SimpleNamespace()
JASCO = SimpleNamespace()
KENT = SimpleNamespace()
LabRAM = SimpleNamespace()
ocean_optics = SimpleNamespace()
PyCMDS = SimpleNamespace()
Shimadzu = SimpleNamespace()
Solis = SimpleNamespace()
spcm = SimpleNamespace()
Tensor27 = SimpleNamespace()
wt5 = SimpleNamespace()


# --- fill ----------------------------------------------------------------------------------------


def _populate_containers():

def _from_files(obj, dirname, prefix=""):
"""Add datasets from files in a directory.

Parameters
Expand All @@ -30,9 +50,9 @@ def _from_files(self, dirname, prefix=""):
"""
for p in (here / dirname).iterdir():
n = prefix + wt_kit.string2identifier(p.name.split(".")[0])
setattr(self, n, p)
setattr(obj, n, p)

def _from_directory(self, dirname, prefix=""):
def _from_directory(obj, dirname, prefix=""):
"""Add dataset from files in a directory.

Parameters
Expand All @@ -44,55 +64,40 @@ def _from_directory(self, dirname, prefix=""):
"""
ps = list((here / dirname).iterdir())
n = prefix + wt_kit.string2identifier(dirname.name)
setattr(self, n, ps)


# --- fill ----------------------------------------------------------------------------------------
setattr(obj, n, ps)

_from_files(BrunoldrRaman, here / "BrunoldrRaman")

BrunoldrRaman = DatasetContainer()
BrunoldrRaman._from_files(here / "BrunoldrRaman")
_from_files(Cary, "Cary")

Cary = DatasetContainer()
Cary._from_files("Cary")
_from_files(COLORS, here / "COLORS" / "v0.2", prefix="v0p2_")
_from_files(COLORS, here / "COLORS" / "v2.2", prefix="v2p2_")

COLORS = DatasetContainer()
COLORS._from_files(here / "COLORS" / "v0.2", prefix="v0p2_")
COLORS._from_files(here / "COLORS" / "v2.2", prefix="v2p2_")
_from_files(JASCO, "JASCO")

JASCO = DatasetContainer()
JASCO._from_files("JASCO")
_from_directory(KENT, here / "KENT" / "LDS821 TRSF")
_from_directory(KENT, here / "KENT" / "LDS821 DOVE")
_from_directory(KENT, here / "KENT" / "PbSe 2D delay B")

KENT = DatasetContainer()
KENT._from_directory(here / "KENT" / "LDS821 TRSF")
KENT._from_directory(here / "KENT" / "LDS821 DOVE")
KENT._from_directory(here / "KENT" / "PbSe 2D delay B")
_from_files(LabRAM, here / "LabRAM")

LabRAM = DatasetContainer()
LabRAM._from_files(here / "LabRAM")
_from_files(ocean_optics, "ocean_optics")

ocean_optics = DatasetContainer()
ocean_optics._from_files("ocean_optics")
_from_files(PyCMDS, "PyCMDS")

PyCMDS = DatasetContainer()
PyCMDS._from_files("PyCMDS")
_from_files(Shimadzu, "Shimadzu")

Shimadzu = DatasetContainer()
Shimadzu._from_files("Shimadzu")
_from_files(Solis, "Solis")

Solis = DatasetContainer()
Solis._from_files("Solis")
_from_files(spcm, "spcm")

spcm = DatasetContainer()
spcm._from_files("spcm")
_from_files(Tensor27, "Tensor27")

Tensor27 = DatasetContainer()
Tensor27._from_files("Tensor27")
_from_files(wt5, here / "wt5" / "v1.0.0", prefix="v1p0p0_")
_from_files(wt5, here / "wt5" / "v1.0.1", prefix="v1p0p1_")

wt5 = DatasetContainer()
wt5._from_files(here / "wt5" / "v1.0.0", prefix="v1p0p0_")
wt5._from_files(here / "wt5" / "v1.0.1", prefix="v1p0p1_")

_populate_containers()

# --- pretty namespace ----------------------------------------------------------------------------

Expand All @@ -103,9 +108,12 @@ def _from_directory(self, dirname, prefix=""):
"COLORS",
"JASCO",
"KENT",
"LabRAM",
"ocean_optics",
"PyCMDS",
"Shimadzu",
"Solis",
"spcm",
"Tensor27",
"wt5",
]
1 change: 0 additions & 1 deletion docs/api/WrightTools.artists.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ WrightTools\.artists module
interact2D
overline_colors
pcolor_helper
plot_colorbar
plot_colormap_components
plot_gridlines
plot_margins
Expand Down
3 changes: 1 addition & 2 deletions docs/artists.rst
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,6 @@ In addition, ``WrightTools`` defines some small helper functions for common task

- Pairs well with :attr:`WrightTools.data.Constant.label`

- :meth:`~WrightTools.artists.plot_colorbar` Add a colorbar in a single function call
- :meth:`~WrightTools.artists.set_fig_labels` Label axes in a whole row/column of a figure

- Allows the use of slice objects to limit range affected
Expand Down Expand Up @@ -311,7 +310,7 @@ In addition, ``WrightTools`` defines some small helper functions for common task
# plot colormap
cax = plt.subplot(gs[1:3, -1])
ticks = np.linspace(data.ai0.min(), data.ai0.max(), 11)
wt.artists.plot_colorbar(cax=cax, label="amplitude", cmap="default", ticks=ticks)
plt.colorbar(cax=cax, label="amplitude", cmap="default", ticks=ticks)
# set axis labels
wt.artists.set_fig_labels(xlabel=data.w1__e__wm.label, ylabel=data.d2.label, col=slice(0, 1))

Expand Down
1 change: 1 addition & 0 deletions docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ wt-convert
Use ``wt-convert`` to explore the WrightTools units system and the conversions of units.

.. code-block:: shell

> wt-units 1330 nm wn
7692.3 wn
0.95372 eV
Expand Down
11 changes: 7 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
language = "en"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
Expand Down Expand Up @@ -236,9 +236,11 @@ def reset_wt(gallery_conf, fname):
# This is an awful hack because python does not allow unloading modules
# This is, however, the same thing upstream sphinx-gallery does for
# seaborn, so it's not _so_ bad I guess. 2019-04-07 KFS
for module in list(sys.modules.keys()):
if module.startswith("WrightTools.datasets"):
del sys.modules[module]
from WrightTools import datasets

datasets_module = sys.modules.get("WrightTools.datasets")
if datasets_module is not None:
datasets._populate_containers()


sphinx_gallery_conf = {
Expand All @@ -247,6 +249,7 @@ def reset_wt(gallery_conf, fname):
"gallery_dirs": "auto_examples",
"backreferences_dir": os.path.join("gen_modules", "backreferences"),
"reset_modules": ["matplotlib", reset_wt],
"reset_module_order": "before",
}


Expand Down
2 changes: 1 addition & 1 deletion docs/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ To choose a specific time point, you can of course just make the chopping more s
data = wt.open(p)
data.transform('w1=wm', 'w2-wm', 'd2')
data.convert('eV')
data1 = data.chop('w2', at={'w1=wm':[1.5, 'eV'], 'd2':[0, 'fs']})[0]
data1 = data.chop('w2-wm', at={'w1=wm':[1.5, 'eV'], 'd2':[0, 'fs']})[0]
wt.artists.quick1D(data1)
plt.show()

Expand Down
5 changes: 3 additions & 2 deletions examples/DOVE_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

p = datasets.KENT.LDS821_DOVE
data = wt.data.from_KENT(p, ignore=["d1", "d2", "wm"], verbose=False)
data.channels[0].normalize()

fig, gs = wt.artists.create_figure(width="double", cols=[1, 1, "cbar"], wspace=0.7)

Expand All @@ -27,11 +28,11 @@
# transformed
ax = plt.subplot(gs[0, 1])
data.transform("w2", "w1-w2")
ax.pcolor(data)
art = ax.pcolor(data)
wt.artists.set_ax_labels(xlabel=data.w2.label)
ax.grid()
ax.set_title("transformed", fontsize=20)

# colorbar
cax = plt.subplot(gs[0, -1])
wt.artists.plot_colorbar(cax, label="Intensity")
fig.colorbar(art, cax=cax, label="Intensity")
Loading
Loading