Skip to content

fix(axis): remove deprecation warning #22

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

Merged
merged 4 commits into from
Apr 29, 2024
Merged
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
27 changes: 21 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,34 @@ import numpy as np
import cosmoplots
import matplotlib as mpl

# Setup
mpl.style.use("cosmoplots.default")
a = np.exp(np.linspace(-3, 5, 100))
a = np.exp(np.linspace(-3, 1, 100))

# Plotting
fig = plt.figure()
ax1 = plt.gca()
ax1.set_xlabel("X Axis")
ax1.set_ylabel("Y Axis")
base = 2 # Default is 10, but 2 works equally well
# Do plotting ...
ax1.semilogx(a)
# It is recommended to call the change_log_axis_base function after doing all the
# plotting. By default, it will try to infer the scaling used for the axis and only
# adjust accordingly.
cosmoplots.change_log_axis_base(ax1, base=base)
# Plotting
fig = plt.figure()
ax = plt.gca()
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax2 = plt.gca()
ax2.set_xlabel("X Axis")
ax2.set_ylabel("Y Axis")
base = 2 # Default is 10, but 2 works equally well
cosmoplots.change_log_axis_base(ax, "x", base=base)
cosmoplots.change_log_axis_base(ax2, "x", base=base)
# Do plotting ...
# If you use "plot", the change_log_axis_base can be called at the top (along with add_axes
# etc.), but using loglog, semilogx, semilogy will re-set, and the change_log_axis_base
# function must be called again.
ax.plot(a)
ax2.plot(a)
plt.show()
```

Expand Down
62 changes: 41 additions & 21 deletions cosmoplots/axes.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,42 @@
"""Module for modifying the axis properties of plots."""

import warnings

from typing import List, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import ticker


def change_log_axis_base(axes: plt.Axes, which: str, base: float = 10) -> plt.Axes:
def _convert_scale_name(scale: str, axis: str) -> str:
"""Convert the scale name to a more readable format."""
# All possible scale names:
# ['asinh', 'function', 'functionlog', 'linear', 'log', 'logit', 'mercator', 'symlog']
return f"{axis}axis" if scale == "log" else "none"


def _check_axes_scales(axes: plt.Axes) -> Tuple[List[str], str]:
xscale, yscale = axes.get_xscale(), axes.get_yscale()
xs, ys = _convert_scale_name(xscale, "x"), _convert_scale_name(yscale, "y")
if xs == "xaxis" and ys == "yaxis":
scales = [xs, ys]
pltype = "loglog"
elif xs == "xaxis":
scales = [xs]
pltype = "semilogx"
elif ys == "yaxis":
scales = [ys]
pltype = "semilogy"
else:
scales = []
pltype = "linear"
return scales, pltype


def change_log_axis_base(
axes: plt.Axes, which: Union[str, None] = None, base: float = 10
) -> plt.Axes:
"""Change the tick formatter to not use powers 0 and 1 in logarithmic plots.

Change the logarithmic axes `10^0 -> 1` and `10^1 -> 10` (or the given base), i.e.
Change the logarithmic axis `10^0 -> 1` and `10^1 -> 10` (or the given base), i.e.
without power, otherwise use the base to some power. For more robust and less error
prone results, the plotting type is also re-set with the same base ('loglog',
'semilogx' and 'semilogy').
Expand All @@ -19,38 +45,32 @@ def change_log_axis_base(axes: plt.Axes, which: str, base: float = 10) -> plt.Ax

Parameters
----------
axes: plt.Axes
axes : plt.Axes
An axes object
which: str
Whether to update both x and y axis, or just one of them.
base: float
which : str | None, optional
Whether to update both x and y axis, or just one of them ("both", "x" or "y").
If no value is given, it defaults to None and the function will try to infer the
axis from the current plotting type. If the axis are already linear, the
function will return the axes object without any changes. Defaults to None.
base : float
The base of the logarithm. Defaults to base 10 (same as loglog, etc.)

Returns
-------
plt.Axes
The updated axes object.

Raises
------
ValueError
If the axes given in `which` is not `x`, `y` or `both`.
"""
warnings.warn(
"The 'change_log_axis_base' function is deprecated and will be removed in the"
" next major version release of cosmoplots, v1.0.0. Instead, use the `mplstyle`"
" files to set the figure dimensions: \nplt.style.use('cosmoplots.default')"
)
if which == "both":
axs, pltype = ["xaxis", "yaxis"], "loglog"
elif which == "x":
axs, pltype = ["xaxis"], "semilogx"
elif which == "y":
axs, pltype = ["yaxis"], "semilogy"
else:
raise ValueError(
"No valid axis found. 'which' must be either of 'both', 'x' or 'y'."
)
axs, pltype = _check_axes_scales(axes)
if not axs and pltype == "linear":
# If both the axes are already linear, just return the axes object silently
return axes
getattr(axes, pltype)(base=base)
for ax in axs:
f = getattr(axes, ax)
Expand Down
Loading