Skip to content

Commit

Permalink
Add colour.plotting.font_scaling definition.
Browse files Browse the repository at this point in the history
  • Loading branch information
KelSolaar committed Nov 5, 2023
1 parent e8ef3b5 commit 6fdb7fa
Show file tree
Hide file tree
Showing 10 changed files with 115 additions and 7 deletions.
19 changes: 19 additions & 0 deletions colour/hints/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
"LiteralOOTFInverse",
"LiteralLUTReadMethod",
"LiteralLUTWriteMethod",
"LiteralFontScaling",
]

RegexFlag = NewType("RegexFlag", re.RegexFlag)
Expand Down Expand Up @@ -558,6 +559,24 @@ def apply(self, RGB: ArrayLike, **kwargs: Any) -> NDArray: # noqa: D102
"Sony SPI3D",
"Sony SPImtx",
]
LiteralFontScaling = Literal[
"xx-small",
"x-small",
"small",
"medium",
"large",
"x-large",
"xx-large",
"larger",
"smaller",
"xx-small-colour-science",
"x-small-colour-science",
"small-colour-science",
"medium-colour-science",
"large-colour-science",
"x-large-colour-science",
"xx-large-colour-science",
]
# LITERALISE::END


Expand Down
3 changes: 3 additions & 0 deletions colour/plotting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"matplotlib.collections",
"matplotlib.colors",
"matplotlib.figure",
"matplotlib.font_manager",
"matplotlib.patches",
"matplotlib.path",
"matplotlib.pyplot",
Expand All @@ -36,6 +37,7 @@
CONSTANTS_ARROW_STYLE,
colour_style,
override_style,
font_scaling,
XYZ_to_plotting_colourspace,
ColourSwatch,
colour_cycle,
Expand Down Expand Up @@ -147,6 +149,7 @@
"CONSTANTS_ARROW_STYLE",
"colour_style",
"override_style",
"font_scaling",
"XYZ_to_plotting_colourspace",
"ColourSwatch",
"colour_cycle",
Expand Down
54 changes: 53 additions & 1 deletion colour/plotting/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- :func:`colour.plotting.colour_style`
- :func:`colour.plotting.override_style`
- :func:`colour.plotting.font_scaling`
- :func:`colour.plotting.XYZ_to_plotting_colourspace`
- :class:`colour.plotting.ColourSwatch`
- :func:`colour.plotting.colour_cycle`
Expand All @@ -29,10 +30,12 @@
import contextlib
import functools
import itertools
from contextlib import contextmanager
from dataclasses import dataclass, field
from functools import partial

import matplotlib.cm
import matplotlib.font_manager
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
Expand All @@ -56,9 +59,11 @@
ArrayLike,
Callable,
Dict,
Generator,
List,
Literal,
LiteralChromaticAdaptationTransform,
LiteralFontScaling,
LiteralRGBColourspace,
Mapping,
NDArrayFloat,
Expand Down Expand Up @@ -96,6 +101,7 @@
"CONSTANTS_ARROW_STYLE",
"colour_style",
"override_style",
"font_scaling",
"XYZ_to_plotting_colourspace",
"ColourSwatch",
"colour_cycle",
Expand Down Expand Up @@ -216,6 +222,15 @@
)
"""Various defaults settings used across the plotting sub-package."""

# NOTE: Adding our font scaling items so that they can be tweaked without
# affecting *Matplotplib* ones.
for _scaling, _value in CONSTANTS_COLOUR_STYLE.font.scaling.items():
matplotlib.font_manager.font_scalings[
f'{_scaling.replace("_", "-")}-colour-science'
] = _value

del _scaling, _value

CONSTANTS_ARROW_STYLE: Structure = Structure(
**{
"color": CONSTANTS_COLOUR_STYLE.colour.dark,
Expand Down Expand Up @@ -360,6 +375,43 @@ def wrapped(*args: Any, **kwargs: Any) -> Any:
return wrapper


@contextmanager
def font_scaling(scaling: LiteralFontScaling, value: float) -> Generator:
"""
Define a context manager setting temporarily a *Matplotlib* font scaling.
Parameters
----------
scaling
Font scaling to temporarily set.
value
Value to temporarily set the font scaling with.
Yields
------
Generator.
Examples
--------
>>> with font_scaling("medium-colour-science", 2):
... print(
... matplotlib.font_manager.font_scalings["medium-colour-science"]
... )
...
2
>>> print(matplotlib.font_manager.font_scalings["medium-colour-science"])
1
"""

current_value = matplotlib.font_manager.font_scalings[scaling]

matplotlib.font_manager.font_scalings[scaling] = value

yield

matplotlib.font_manager.font_scalings[scaling] = current_value


def XYZ_to_plotting_colourspace(
XYZ: ArrayLike,
illuminant: ArrayLike = RGB_COLOURSPACES["sRGB"].whitepoint,
Expand Down Expand Up @@ -726,7 +778,7 @@ def label_rectangles(
labels: Sequence[str],
rectangles: Sequence[Patch],
rotation: Literal["horizontal", "vertical"] | str = "vertical",
text_size: float = 10,
text_size: float = CONSTANTS_COLOUR_STYLE.font.scaling.medium,
offset: ArrayLike | None = None,
**kwargs: Any,
) -> Tuple[Figure, Axes]:
Expand Down
2 changes: 1 addition & 1 deletion colour/plotting/diagrams.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ def plot_spectral_locus(
clip_on=True,
ha="left" if lines_w["normal"][::2][i, 0] >= 0 else "right",
va="center",
fontsize="x-small",
fontsize="x-small-colour-science",
zorder=CONSTANTS_COLOUR_STYLE.zorder.background_label,
)

Expand Down
2 changes: 1 addition & 1 deletion colour/plotting/temperature.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ def plot_planckian_locus(
clip_on=True,
ha="left",
va="bottom",
fontsize="x-small",
fontsize="x-small-colour-science",
zorder=CONSTANTS_COLOUR_STYLE.zorder.foreground_label,
)

Expand Down
27 changes: 25 additions & 2 deletions colour/plotting/tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import unittest
from functools import partial

import matplotlib.font_manager
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.axes import Axes
Expand All @@ -28,6 +29,7 @@
filter_illuminants,
filter_passthrough,
filter_RGB_colourspaces,
font_scaling,
label_rectangles,
override_style,
plot_image,
Expand All @@ -51,7 +53,8 @@
__all__ = [
"TestColourStyle",
"TestOverrideStyle",
"TestXyzToPlottingColourspace",
"TestFontScaling",
"TestXYZToPlottingColourspace",
"TestColourCycle",
"TestArtist",
"TestCamera",
Expand Down Expand Up @@ -107,7 +110,27 @@ def test_text_color_override():
plt.rcParams["text.color"] = text_color


class TestXyzToPlottingColourspace(unittest.TestCase):
class TestFontScaling(unittest.TestCase):
"""
Define :func:`colour.plotting.common.font_scaling` definition unit tests
methods.
"""

def test_font_scaling(self):
"""Test :func:`colour.plotting.common.font_scaling` definition."""

with font_scaling("medium-colour-science", 2):
self.assertEqual(
matplotlib.font_manager.font_scalings["medium-colour-science"],
2,
)

self.assertEqual(
matplotlib.font_manager.font_scalings["medium-colour-science"], 1
)


class TestXYZToPlottingColourspace(unittest.TestCase):
"""
Define :func:`colour.plotting.common.XYZ_to_plotting_colourspace`
definition unit tests methods.
Expand Down
4 changes: 2 additions & 2 deletions colour/plotting/tm3018/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ def plot_16_bin_bars(
label_template.format(value),
xy=(i + 1, value + vo),
rotation=90,
fontsize="xx-small",
fontsize="xx-small-colour-science",
ha="center",
va=va,
zorder=CONSTANTS_COLOUR_STYLE.zorder.midground_label,
Expand All @@ -571,7 +571,7 @@ def plot_16_bin_bars(
axes.annotate(
label_template.format(value),
xy=(i + 1, value + vo),
fontsize="xx-small",
fontsize="xx-small-colour-science",
ha="center",
va=va,
zorder=CONSTANTS_COLOUR_STYLE.zorder.midground_label,
Expand Down
1 change: 1 addition & 0 deletions docs/colour.hints.rst
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,4 @@ Annotation Type Hints
LiteralOOTFInverse
LiteralLUTReadMethods
LiteralLUTWriteMethods
LiteralFontScaling
1 change: 1 addition & 0 deletions docs/colour.plotting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Common
KwargsArtist
KwargsCamera
KwargsRender
font_scaling
filter_passthrough
filter_RGB_colourspaces
filter_cmfs
Expand Down
9 changes: 9 additions & 0 deletions utilities/literalise.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import sys
from textwrap import dedent

import matplotlib.font_manager

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

import colour # noqa: E402
Expand Down Expand Up @@ -44,6 +46,12 @@ def literalise(path_module_hints: str = PATH_MODULE_HINTS):
with open(path_module_hints) as file_module_hints:
content = file_module_hints.read()

font_scalings = [
scaling
for scaling in matplotlib.font_manager.font_scalings
if scaling is not None
]

content = re.sub(
"# LITERALISE::BEGIN.*?# LITERALISE::END",
dedent(
Expand All @@ -65,6 +73,7 @@ def literalise(path_module_hints: str = PATH_MODULE_HINTS):
LiteralOOTFInverse = Literal{sorted(colour.OOTF_INVERSES)}
LiteralLUTReadMethod = Literal{sorted(colour.io.LUT_READ_METHODS)}
LiteralLUTWriteMethod = Literal{sorted(colour.io.LUT_WRITE_METHODS)}
LiteralFontScaling = Literal{font_scalings}
# LITERALISE::END
"""
).strip(),
Expand Down

0 comments on commit 6fdb7fa

Please sign in to comment.