Skip to content

feat(combine): reads font from the "font.serif" matplotlib param by default #25

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 7 commits into from
May 8, 2024
Merged
47 changes: 42 additions & 5 deletions cosmoplots/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,50 @@

# `Self` was introduced in 3.11, but returning the class type works from 3.7 onwards.
from __future__ import annotations
import warnings

import logging
import pathlib
import subprocess
import tempfile
import warnings
from contextlib import contextmanager

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties, findfont


@contextmanager
def _ignore_logging_context():
loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
# turn loggers off
for logger in loggers:
logger.disabled = True
logging.root.disabled = True
yield
# turn loggers back on
for logger in loggers:
logger.disabled = False
logging.root.disabled = False


class Combine:
"""Combine images into a subfigure layout."""

def __init__(self) -> None:
self._gravity = "northwest"
self._fontsize = 100
self._pos = (10.0, 10.0)
self._font = "Times-New-Roman"
with _ignore_logging_context():
font = findfont(FontProperties(family=plt.rcParams["font.serif"]))
self._font = font
self._fontsize = int(plt.rcParams["font.size"])
self._color = "black"
self._ft: str = ".png"
self._output = pathlib.Path(f"output{self._ft}")
self._dpi = (
plt.rcParams["savefig.dpi"]
if isinstance(plt.rcParams["savefig.dpi"], float)
else plt.rcParams["figure.dpi"]
)
self._files: list[pathlib.Path] = []
self._labels: list[str] = []
self._w: int | None = None
Expand Down Expand Up @@ -67,7 +93,8 @@ def using(
The type of font to use, default is Times New Roman. See `convert -list
font` for a list of available fonts.
fontsize : int, optional
The size of the font in pointsize. Default is `100`.
The size of the font in pointsize. Default is to use the "font.size" field
in the matplotlib rcParams.
color : str, optional
The color of the text. Default is `black`.
"""
Expand Down Expand Up @@ -132,14 +159,20 @@ def _create_labels(self) -> list[str]:
count += 1
return characters

def save(self, output: pathlib.Path | str | None = None) -> None:
def save(
self, output: pathlib.Path | str | None = None, dpi: float | int | None = None
) -> None:
"""Save the combined images as a png file.

Parameters
----------
output : pathlib.Path | str, optional
Give the name of the output file, default is `output.png`.
dpi : float | int, optional
The resolution that the input files were saved with. Default is the same as
the matplotlib savefig dpi.
"""
self._dpi = dpi or self._dpi
self._check_params_before_save(output)
self._check_cli_available()
self._run_subprocess()
Expand Down Expand Up @@ -198,7 +231,11 @@ def _run_subprocess(self) -> None:
subprocess.call(
[
"convert",
"-units",
"PixelsPerInch",
file,
"-density",
str(self._dpi),
"-font",
self._font,
"-pointsize",
Expand Down
4 changes: 3 additions & 1 deletion tests/test_concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ def test_convert_help() -> None:

def test_help(capfd) -> None:
"""Test the `help` method."""
cosmoplots.Combine().help()
# By default, the '.ttf' file is specified, but that's hard to test against.
plt.rcParams["font.size"] = 100
cosmoplots.Combine().using(font="Times-New-Roman").help()
out, err = capfd.readouterr()
help = (
"To create images with labels:\n"
Expand Down
Loading