codex/font-size-and-x-height.py

font-size-and-x-height.py
"""Compare two original toy letterforms at one EM scale; output PNG in cwd."""
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon, Rectangle


def toy_x(height):
    left, right, middle = 0.25, 0.75, 0.5
    return [
        (left, 0), (left + 0.11, 0), (middle, height * 0.37),
        (right - 0.11, 0), (right, 0), (middle + 0.06, height * 0.5),
        (right, height), (right - 0.11, height),
        (middle, height * 0.63), (left + 0.11, height),
        (left, height), (middle - 0.06, height * 0.5),
    ]


def main():
    fig = plt.figure(figsize=(8.6, 4.2), dpi=100, facecolor="white")
    fig.suptitle("Same font size, different lowercase heights", y=0.97,
                 fontsize=17, weight="bold", color="#172330")
    fig.text(0.5, 0.87, "Both nominal scales: 16 pixels per em",
             ha="center", fontsize=12, color="#45535d")
    for left, height, label, color in [
        (0.06, 0.45, "Toy design A", "#246a91"),
        (0.55, 0.60, "Toy design B", "#a85125"),
    ]:
        ax = fig.add_axes([left, 0.25, 0.38, 0.52])
        ax.add_patch(Rectangle((0, 0), 1, 1, facecolor="#f5f7f8",
                               edgecolor="#a7b1b8", linewidth=1,
                               linestyle="--"))
        ax.add_patch(Polygon(toy_x(height), closed=True,
                             facecolor=color, edgecolor="none"))
        ax.axhline(0, color="#465963", linewidth=1)
        ax.plot([0, 1], [height, height], color=color, linestyle=":")
        ax.annotate("", xy=(1.08, 0), xytext=(1.08, 1),
                    arrowprops={"arrowstyle": "<->", "color": "#6e7c84"})
        ax.text(1.13, 0.5, "1 em", rotation=90, va="center", fontsize=10)
        ax.text(0.5, 1.08, label, ha="center", va="bottom",
                fontsize=12, color=color, weight="bold")
        ax.text(0.5, -0.13, "baseline", ha="center", fontsize=10,
                color="#45535d")
        ax.set_xlim(-0.04, 1.24)
        ax.set_ylim(-0.2, 1.18)
        ax.axis("off")
        fig.text(left + 0.17, 0.18,
                 f"x-height: {height:.2f} em = {16 * height:.1f} pixels",
                 ha="center", fontsize=11, color=color)
    fig.text(0.5, 0.075,
             "B's lowercase body is one third taller, despite an identical nominal scale.",
             ha="center", fontsize=11, color="#45535d")
    fig.text(0.5, 0.025,
             "Original schematic letterforms; not measured fonts or rasterized pixel shapes.",
             ha="center", fontsize=10, color="#45535d")
    fig.savefig(Path.cwd() / (Path(__file__).stem + ".png"), dpi=100,
                facecolor="white", transparent=False)
    plt.close(fig)


if __name__ == "__main__":
    main()