diff --git a/.gitignore b/.gitignore index f5885fb..09e9e36 100644 --- a/.gitignore +++ b/.gitignore @@ -17,4 +17,7 @@ coverage.xml htmlcov # gh-pages build script output -/gh-pages \ No newline at end of file +/gh-pages + +# OS Files +.DS_Store diff --git a/build.py b/build.py index 8f094ac..fe629d3 100644 --- a/build.py +++ b/build.py @@ -142,7 +142,7 @@ def load_palette() -> Palette: ) -def codegen(palette: Palette) -> str: +def palette_codegen(palette: Palette) -> str: """Generate contents of `catppuccin/palette.py`.""" lines = [ HEADER, @@ -152,28 +152,9 @@ def codegen(palette: Palette) -> str: return "\n".join(lines) -if __name__ == "__main__": - # we build from the latest palette data rather than a stale `catppuccin.PALETTE`. - # `catppuccin.PALETTE` gets rewritten later, but even then we'd have to - # reload a bunch of modules to get it loaded. - palette = load_palette() - - print("running codegen") - palette_path = Path.cwd() / "catppuccin" / "palette.py" - with palette_path.open("w", newline="\n") as f: - f.write(codegen(palette)) - print("formatting with ruff") - ruff_format = f"ruff format {palette_path}" - subprocess.run(ruff_format.split(), check=True, stdout=subprocess.DEVNULL) - print("palette.py generation complete") - - # Generate the matplotlib styles - print("generating matplotlib styles") - from catppuccin.extras.matplotlib import CATPPUCCIN_STYLE_DIRECTORY - - template_text = ( - CATPPUCCIN_STYLE_DIRECTORY / "_catppuccin_template.txt" - ).read_text() +def generate_mpl_styles(palette: Palette) -> None: + """Generate the matplotlib .mplstyle files.""" + template_text = (Path.cwd() / "matplotlib_template.txt").read_text() for key, flavor in asdict(palette).items(): print(f"- {key}") @@ -184,13 +165,13 @@ def codegen(palette: Palette) -> str: f"<{color}>", flavor["colors"][color]["hex"].replace("#", ""), ) - style_path = CATPPUCCIN_STYLE_DIRECTORY / f"{key}.mplstyle" + style_path = Path.cwd() / "catppuccin" / f"{key}.mplstyle" with style_path.open("w", newline="\n") as f: f.write(text) - print("matplotlib styles generation complete") - # Generate the IPython themes - print("generating ipython themes") + +def generate_ipython_themes(palette: Palette) -> None: + """Generate the IPython theme JSON files.""" IPYTHON_THEME_DIRECTORY.mkdir(exist_ok=True) for flavor in palette: for theme in (ipython_theme(flavor), ipython_noitalic_theme(flavor)): @@ -199,4 +180,31 @@ def codegen(palette: Palette) -> str: with theme_path.open("w", newline="\n") as f: json.dump(theme, f, indent=2) f.write("\n") + + +def main() -> None: # noqa: D103 + # we build from the latest palette data rather than a stale `catppuccin.PALETTE`. + # `catppuccin.PALETTE` gets rewritten below, but even then we'd have to + # reload a bunch of modules to get it loaded. + palette = load_palette() + + print("running palette codegen") + palette_path = Path.cwd() / "catppuccin" / "palette.py" + with palette_path.open("w", newline="\n") as f: + f.write(palette_codegen(palette)) + print("formatting with ruff") + ruff_format = f"ruff format {palette_path}" + subprocess.run(ruff_format.split(), check=True, stdout=subprocess.DEVNULL) + print("palette.py generation complete") + + print("generating matplotlib styles") + generate_mpl_styles(palette) + print("matplotlib styles generation complete") + + print("generating ipython themes") + generate_ipython_themes(palette) print("ipython themes generation complete") + + +if __name__ == "__main__": + main() diff --git a/catppuccin/__init__.py b/catppuccin/__init__.py index 352123a..4385b90 100644 --- a/catppuccin/__init__.py +++ b/catppuccin/__init__.py @@ -89,9 +89,6 @@ from catppuccin.palette import PALETTE as PALETTE -# Attempt to register styles and colormaps if matplotlib is available +# Register colormaps if matplotlib is available if importlib.util.find_spec("matplotlib") is not None: - from catppuccin.extras.matplotlib import _register_colormap_list, _register_styles - - _register_styles() - _register_colormap_list() + import catppuccin.extras.matplotlib # noqa: F401 diff --git a/catppuccin/extras/matplotlib.py b/catppuccin/extras/matplotlib.py index 515bcc0..80aa59a 100644 --- a/catppuccin/extras/matplotlib.py +++ b/catppuccin/extras/matplotlib.py @@ -7,107 +7,112 @@ The library tries to register styles and colormaps if `matplotlib` is installed. See the examples below for some use cases: -1. Load a style, using `mpl.style.use` +1. Load a style, using `plt.style.use` - ```python - import catppuccin - import matplotlib as mpl - import matplotlib.pyplot as plt + ```python + import matplotlib.pyplot as plt - mpl.style.use(catppuccin.PALETTE.mocha.identifier) - plt.plot([0,1,2,3], [1,2,3,4]) - plt.show() - ``` + plt.style.use("catppuccin.mocha") + plt.plot([0,1,2,3], [1,2,3,4]) + plt.show() + ``` 1. Mix it with different stylesheets! - ```python - import catppuccin - import matplotlib as mpl - import matplotlib.pyplot as plt + ```python + import matplotlib.pyplot as plt - mpl.style.use(["ggplot", catppuccin.PALETTE.mocha.identifier]) - plt.plot([0,1,2,3], [1,2,3,4]) - plt.show() - ``` + plt.style.use(["ggplot", "catppuccin.mocha"]) + plt.plot([0,1,2,3], [1,2,3,4]) + plt.show() + ``` + +1. Pick the style from a flavor, using `style_name` + + ```python + import catppuccin + import matplotlib.pyplot as plt + from catppuccin.extras.matplotlib import style_name + + flavor = catppuccin.PALETTE.latte + plt.style.use(style_name(flavor)) + plt.plot([0,1,2,3], [1,2,3,4]) + plt.show() + ``` 1. Load individual colors - ```python - import matplotlib.pyplot as plt - import catppuccin - from catppuccin.extras.matplotlib import load_color + ```python + import matplotlib.pyplot as plt + import catppuccin + + plt.plot([0,1,2,3], [1,2,3,4], color=catppuccin.PALETTE.latte.colors.peach.hex) + plt.show() + ``` + +1. Just use the colormaps in your plots + + ```python + import matplotlib.pyplot as plt + import numpy as np - color = load_color(catppuccin.PALETTE.latte.identifier, "peach") - plt.plot([0,1,2,3], [1,2,3,4], color=color) - plt.show() - ``` + rng = np.random.default_rng() + data = rng.integers(10, size=(30, 30)) + + plt.imshow(data, cmap="catppuccin.mocha") + plt.show() + ``` 1. Define custom colormaps - ```python - import matplotlib.pyplot as plt - import numpy as np - import catppuccin - from catppuccin.extras.matplotlib import get_colormap_from_list - - cmap = get_colormap_from_list( - catppuccin.PALETTE.frappe.identifier, - ["red", "peach", "yellow", "green"], - ) - rng = np.random.default_rng() - data = rng.integers(2, size=(30, 30)) - - plt.imshow(data, cmap=cmap) - plt.show() - ``` + ```python + import matplotlib.pyplot as plt + import numpy as np + import catppuccin + from matplotlib.colors import LinearSegmentedColormap + + cmap = LinearSegmentedColormap.from_list( + "my_custom_palette", + [ + color.hex for color in catppuccin.PALETTE.frappe.colors + if color.identifier in ["red", "peach", "yellow", "green"] + ], + ) + rng = np.random.default_rng() + data = rng.integers(10, size=(30, 30)) + + plt.imshow(data, cmap=cmap) + plt.show() + ``` """ from __future__ import annotations -from dataclasses import asdict -from pathlib import Path -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING import matplotlib as mpl import matplotlib.colors -import matplotlib.style from catppuccin.palette import PALETTE if TYPE_CHECKING: - from collections.abc import Iterable - -CATPPUCCIN_STYLE_DIRECTORY = Path(__file__).parent / "matplotlib_styles" -DEFAULT_COLORMAP_COLORS = ("base", "blue") - - -def _register_styles() -> None: - """Register the included stylesheets in the mpl style library.""" - for path in CATPPUCCIN_STYLE_DIRECTORY.glob("*.mplstyle"): - style = mpl.rc_params_from_file(path, use_default_template=False) - mpl.style.library.setdefault(path.stem, mpl.RcParams()).update(style) + from catppuccin.models import Flavor +DEFAULT_COLORMAP_COLORS = ("blue", "teal", "yellow", "peach", "red") -def _register_colormap_list() -> None: - """Register the included color maps in the `matplotlib` colormap library.""" - for palette_name in asdict(PALETTE): - cmap = get_colormap_from_list(palette_name, DEFAULT_COLORMAP_COLORS) - mpl.colormaps.register(cmap=cmap, name=palette_name, force=True) +def style_name(flavor: Flavor) -> str: + """Name of the matplotlib style for a flavor, for use with `plt.style.use`. -def get_colormap_from_list( - palette_name: str, - color_names: Iterable[str], -) -> matplotlib.colors.LinearSegmentedColormap: - """Get a `matplotlib` colormap from a list of colors for a specific palette.""" - colors = [load_color(palette_name, color_name) for color_name in color_names] - return matplotlib.colors.LinearSegmentedColormap.from_list(palette_name, colors) + The flavor's colormap is registered under the same name. + """ + return f"catppuccin.{flavor.identifier}" -def load_color(palette_name: str, color_name: str) -> str: - """Load the color for a given palette and color name.""" - return cast( - str, - PALETTE.__getattribute__(palette_name).colors.__getattribute__(color_name).hex, +# Register the included color maps in the `matplotlib` colormap library. +for _palette in PALETTE: + _cmap = matplotlib.colors.LinearSegmentedColormap.from_list( + style_name(_palette), + [getattr(_palette.colors, name).hex for name in DEFAULT_COLORMAP_COLORS], ) + mpl.colormaps.register(cmap=_cmap, force=True) diff --git a/catppuccin/extras/matplotlib_styles/frappe.mplstyle b/catppuccin/frappe.mplstyle similarity index 97% rename from catppuccin/extras/matplotlib_styles/frappe.mplstyle rename to catppuccin/frappe.mplstyle index 40746c5..ea55b97 100644 --- a/catppuccin/extras/matplotlib_styles/frappe.mplstyle +++ b/catppuccin/frappe.mplstyle @@ -6,7 +6,7 @@ # Main colors: blue, peach, green, red, mauve, maroon, pink, rosewater, teal, lavender axes.prop_cycle: cycler('color', ['8caaee', 'ef9f76', 'a6d189', 'e78284', 'ca9ee6', 'ea999c', 'f4b8e4', 'f2d5cf', '81c8be', 'babbf1']) -image.cmap: frappe +image.cmap: catppuccin.frappe # Font color: Text text.color: c6d0f5 diff --git a/catppuccin/extras/matplotlib_styles/latte.mplstyle b/catppuccin/latte.mplstyle similarity index 97% rename from catppuccin/extras/matplotlib_styles/latte.mplstyle rename to catppuccin/latte.mplstyle index bfb3172..59e88b6 100644 --- a/catppuccin/extras/matplotlib_styles/latte.mplstyle +++ b/catppuccin/latte.mplstyle @@ -6,7 +6,7 @@ # Main colors: blue, peach, green, red, mauve, maroon, pink, rosewater, teal, lavender axes.prop_cycle: cycler('color', ['1e66f5', 'fe640b', '40a02b', 'd20f39', '8839ef', 'e64553', 'ea76cb', 'dc8a78', '179299', '7287fd']) -image.cmap: latte +image.cmap: catppuccin.latte # Font color: Text text.color: 4c4f69 diff --git a/catppuccin/extras/matplotlib_styles/macchiato.mplstyle b/catppuccin/macchiato.mplstyle similarity index 97% rename from catppuccin/extras/matplotlib_styles/macchiato.mplstyle rename to catppuccin/macchiato.mplstyle index 4dd3e29..0a9dc85 100644 --- a/catppuccin/extras/matplotlib_styles/macchiato.mplstyle +++ b/catppuccin/macchiato.mplstyle @@ -6,7 +6,7 @@ # Main colors: blue, peach, green, red, mauve, maroon, pink, rosewater, teal, lavender axes.prop_cycle: cycler('color', ['8aadf4', 'f5a97f', 'a6da95', 'ed8796', 'c6a0f6', 'ee99a0', 'f5bde6', 'f4dbd6', '8bd5ca', 'b7bdf8']) -image.cmap: macchiato +image.cmap: catppuccin.macchiato # Font color: Text text.color: cad3f5 diff --git a/catppuccin/extras/matplotlib_styles/mocha.mplstyle b/catppuccin/mocha.mplstyle similarity index 97% rename from catppuccin/extras/matplotlib_styles/mocha.mplstyle rename to catppuccin/mocha.mplstyle index 86dc333..c558965 100644 --- a/catppuccin/extras/matplotlib_styles/mocha.mplstyle +++ b/catppuccin/mocha.mplstyle @@ -6,7 +6,7 @@ # Main colors: blue, peach, green, red, mauve, maroon, pink, rosewater, teal, lavender axes.prop_cycle: cycler('color', ['89b4fa', 'fab387', 'a6e3a1', 'f38ba8', 'cba6f7', 'eba0ac', 'f5c2e7', 'f5e0dc', '94e2d5', 'b4befe']) -image.cmap: mocha +image.cmap: catppuccin.mocha # Font color: Text text.color: cdd6f4 diff --git a/example_plots.py b/example_plots.py index 7fe5695..69461bf 100644 --- a/example_plots.py +++ b/example_plots.py @@ -1,23 +1,22 @@ """Functions to plot some images using matplotlib.""" -from __future__ import annotations - from dataclasses import asdict -import matplotlib as mpl import matplotlib.patches as mpatches import matplotlib.pyplot as plt import numpy as np -from catppuccin.palette import PALETTE +from catppuccin import PALETTE +from catppuccin.extras.matplotlib import style_name +from catppuccin.models import Flavor SEED = 0 POINTS = 50 -def plot_palette(palette_name: str) -> plt.Figure: # type: ignore [name-defined] +def plot_palette(palette: Flavor) -> plt.Figure: # type: ignore [name-defined] """Plot a palette with color names and hex values.""" - colors = asdict(PALETTE.__getattribute__(palette_name).colors) + colors = asdict(palette.colors) # Create figure and adjust figure height to number of colormaps nrows = len(colors) @@ -25,7 +24,7 @@ def plot_palette(palette_name: str) -> plt.Figure: # type: ignore [name-defined fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh)) fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh, left=0.2, right=0.99) - axs[0].set_title(palette_name, fontsize=14) + axs[0].set_title(palette.name, fontsize=14) for ax, color_name in zip(axs, colors, strict=True): ax.hlines(0, 0, 1, colors=colors[color_name]["hex"], linewidth=15) @@ -128,45 +127,14 @@ def example_imshow() -> plt.Figure: # type: ignore [name-defined] return fig -def plot_examples(colormap_list: list[str]) -> None: - """Plot data with associated colormap.""" - rng = np.random.default_rng(SEED) - data = rng.random((30, 30)) - n = len(colormap_list) - fig, axs = plt.subplots( - 1, n, figsize=(n * 2 + 2, 3), constrained_layout=True, squeeze=False - ) - for [ax, cmap] in zip(axs.flat, colormap_list, strict=True): - psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=0.0, vmax=1.0) - fig.colorbar(psm, ax=ax) - plt.show() - - -example_plots = { - "plot": example_plot, - "scatter": example_scatter, - "boxplot": example_boxplot, - "bar": example_bar, - "patches": example_patches, - "imshow": example_imshow, -} - if __name__ == "__main__": - palette_name = "mocha" - mpl.style.use(palette_name) - plot_palette(palette_name) - plt.show() + flavor = PALETTE.mocha + plt.style.use(style_name(flavor)) + plot_palette(flavor) example_plot() - plt.show() example_scatter() - plt.show() example_boxplot() - plt.show() example_bar() - plt.show() example_patches() - plt.show() example_imshow() plt.show() - plot_examples(list(asdict(PALETTE).keys())) - plt.show() diff --git a/catppuccin/extras/matplotlib_styles/_catppuccin_template.txt b/matplotlib_template.txt similarity index 97% rename from catppuccin/extras/matplotlib_styles/_catppuccin_template.txt rename to matplotlib_template.txt index 4ba20af..888b1cb 100644 --- a/catppuccin/extras/matplotlib_styles/_catppuccin_template.txt +++ b/matplotlib_template.txt @@ -6,7 +6,7 @@ # Main colors: blue, peach, green, red, mauve, maroon, pink, rosewater, teal, lavender axes.prop_cycle: cycler('color', ['', '', '', '', '', '', '', '', '', '']) -image.cmap: +image.cmap: catppuccin. # Font color: Text text.color: diff --git a/pyproject.toml b/pyproject.toml index 16b5ad6..8125bfc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ catppuccin-mocha = "catppuccin.extras:ipython_themes" "catppuccin-mocha:noitalic" = "catppuccin.extras:ipython_themes" [project.optional-dependencies] -matplotlib = ["matplotlib>=3.8.4"] +matplotlib = ["matplotlib>=3.10.0"] pygments = ["pygments>=2.17.2"] rich = ["rich>=13.7.0"] ipython = ["ipython>=9.18.0"] diff --git a/tests/test_matplotlib.py b/tests/test_matplotlib.py index 84c9131..8102890 100644 --- a/tests/test_matplotlib.py +++ b/tests/test_matplotlib.py @@ -1,18 +1,30 @@ -from dataclasses import asdict - import matplotlib as mpl +import matplotlib.pyplot as plt import pytest -import catppuccin +from catppuccin import PALETTE +from catppuccin.extras.matplotlib import style_name +from catppuccin.models import Flavor + + +@pytest.mark.parametrize("flavor", list(PALETTE), ids=lambda f: f.identifier) +def test_matplotlib_uses_style(flavor: Flavor) -> None: + plt.style.use(style_name(flavor)) + + +@pytest.mark.parametrize("flavor", list(PALETTE), ids=lambda f: f.identifier) +def test_matplotlib_cmaps(flavor: Flavor) -> None: + assert style_name(flavor) in list(mpl.colormaps) + + +@pytest.mark.parametrize("flavor", list(PALETTE), ids=lambda f: f.identifier) +def test_matplotlib_cmap_uses_flavor_colors(flavor: Flavor) -> None: + cmap = mpl.colormaps[style_name(flavor)] + assert mpl.colors.to_hex(cmap(0.0)) == flavor.colors.blue.hex + assert mpl.colors.to_hex(cmap(1.0)) == flavor.colors.red.hex -@pytest.mark.parametrize( - "name", - [ - catppuccin.PALETTE.__getattribute__(key).identifier - for key in asdict(catppuccin.PALETTE) - ], -) -def test_matplotlib_uses_style(name: str) -> None: - """Test that the matplotlib style is set to the given name.""" - mpl.style.use(name) +@pytest.mark.parametrize("flavor", list(PALETTE), ids=lambda f: f.identifier) +def test_matplotlib_style_sets_cmap(flavor: Flavor) -> None: + with plt.style.context(style_name(flavor)): + assert mpl.rcParams["image.cmap"] == style_name(flavor) diff --git a/uv.lock b/uv.lock index 5f55361..976b815 100644 --- a/uv.lock +++ b/uv.lock @@ -116,7 +116,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "ipython", marker = "extra == 'ipython'", specifier = ">=9.18.0" }, - { name = "matplotlib", marker = "extra == 'matplotlib'", specifier = ">=3.8.4" }, + { name = "matplotlib", marker = "extra == 'matplotlib'", specifier = ">=3.10.0" }, { name = "pdoc", marker = "extra == 'gh-pages'", specifier = ">=15.0.1" }, { name = "pygments", marker = "extra == 'pygments'", specifier = ">=2.17.2" }, { name = "rich", marker = "extra == 'rich'", specifier = ">=13.7.0" },