Skip to content

fonts

The fonts module manages Metropolis font registration with matplotlib.

Module Overview

This module provides:

  • Automatic font registration with matplotlib
  • Font availability checking
  • Access to bundled font files
  • 18 Metropolis font files (9 weights × 2 styles)

Functions

register_metropolis_fonts(verbose=False)

Register Metropolis fonts with matplotlib.

This function finds all Metropolis .ttf files and registers them with matplotlib's font manager. After calling this function, you can use 'Metropolis' as a font family in matplotlib plots.

Args: verbose: If True, print registration messages

Returns: True if fonts were registered successfully, False otherwise

Examples: >>> from msuthemes.fonts import register_metropolis_fonts >>> import matplotlib.pyplot as plt >>> >>> register_metropolis_fonts() >>> plt.rcParams['font.family'] = 'Metropolis' >>> plt.title('MSU Branded Plot', fontfamily='Metropolis')

Source code in msuthemes/fonts/__init__.py
def register_metropolis_fonts(verbose: bool = False) -> bool:
    """Register Metropolis fonts with matplotlib.

    This function finds all Metropolis .ttf files and registers them with
    matplotlib's font manager. After calling this function, you can use
    'Metropolis' as a font family in matplotlib plots.

    Args:
        verbose: If True, print registration messages

    Returns:
        True if fonts were registered successfully, False otherwise

    Examples:
        >>> from msuthemes.fonts import register_metropolis_fonts
        >>> import matplotlib.pyplot as plt
        >>>
        >>> register_metropolis_fonts()
        >>> plt.rcParams['font.family'] = 'Metropolis'
        >>> plt.title('MSU Branded Plot', fontfamily='Metropolis')
    """
    try:
        import matplotlib.font_manager as fm
    except ImportError:
        warnings.warn(
            "matplotlib is not installed. Cannot register fonts.",
            ImportWarning
        )
        return False

    font_dir = get_font_path()

    if not font_dir.exists():
        warnings.warn(
            f"Font directory not found: {font_dir}",
            RuntimeWarning
        )
        return False

    # Find all .ttf files
    font_files = list(font_dir.glob("*.ttf"))

    if not font_files:
        warnings.warn(
            f"No .ttf font files found in {font_dir}",
            RuntimeWarning
        )
        return False

    # Register each font
    registered_count = 0
    for font_file in font_files:
        try:
            fm.fontManager.addfont(str(font_file))
            registered_count += 1
            if verbose:
                print(f"Registered: {font_file.name}")
        except Exception as e:
            if verbose:
                print(f"Failed to register {font_file.name}: {e}")

    if verbose:
        print(f"\nSuccessfully registered {registered_count}/{len(font_files)} Metropolis fonts")

    # Rebuild font cache
    try:
        fm.fontManager._rebuild()
    except AttributeError:
        # Newer versions of matplotlib may not have _rebuild()
        pass

    return registered_count > 0

is_metropolis_available()

Check if Metropolis font is available in matplotlib.

Returns: True if Metropolis font is available, False otherwise

Examples: >>> if is_metropolis_available(): ... plt.rcParams['font.family'] = 'Metropolis' ... else: ... print("Metropolis font not available")

Source code in msuthemes/fonts/__init__.py
def is_metropolis_available() -> bool:
    """Check if Metropolis font is available in matplotlib.

    Returns:
        True if Metropolis font is available, False otherwise

    Examples:
        >>> if is_metropolis_available():
        ...     plt.rcParams['font.family'] = 'Metropolis'
        ... else:
        ...     print("Metropolis font not available")
    """
    try:
        import matplotlib.font_manager as fm

        # Get list of available font families
        available_fonts = {f.name for f in fm.fontManager.ttflist}

        return 'Metropolis' in available_fonts
    except ImportError:
        return False

get_font_path()

Get the path to the Metropolis font directory.

Returns: Path object pointing to the fonts directory

Examples: >>> font_path = get_font_path() >>> print(font_path) PosixPath('.../msuthemes/fonts/metropolis')

Source code in msuthemes/fonts/__init__.py
def get_font_path() -> Path:
    """Get the path to the Metropolis font directory.

    Returns:
        Path object pointing to the fonts directory

    Examples:
        >>> font_path = get_font_path()
        >>> print(font_path)
        PosixPath('.../msuthemes/fonts/metropolis')
    """
    return Path(__file__).parent / "metropolis"

Usage Examples

Automatic Registration

from msuthemes import theme_msu

# Fonts are automatically registered
theme_msu()

Manual Registration

from msuthemes import register_metropolis_fonts

# Manually register fonts
register_metropolis_fonts()

Check Font Availability

from msuthemes import is_metropolis_available

if is_metropolis_available():
    print("Metropolis fonts are ready")
else:
    print("Need to register fonts")

Get Font File Path

from msuthemes.fonts import get_font_path

# Get path to specific font
regular_path = get_font_path('Metropolis-Regular.otf')
bold_path = get_font_path('Metropolis-Bold.otf')

print(f"Regular font: {regular_path}")
print(f"Bold font: {bold_path}")

Using Specific Font Weights

from msuthemes import theme_msu
import matplotlib.pyplot as plt

# Apply theme (registers fonts)
theme_msu()

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 2])

# Use different font weights
ax.set_title('Title in Default Weight', fontsize=16)
ax.set_xlabel('Light Weight', fontweight='light')
ax.set_ylabel('Bold Weight', fontweight='bold')

plt.show()

Font Files

The following Metropolis font files are included:

Regular Styles: - Metropolis-Thin.otf - Metropolis-ExtraLight.otf - Metropolis-Light.otf - Metropolis-Regular.otf - Metropolis-Medium.otf - Metropolis-SemiBold.otf - Metropolis-Bold.otf - Metropolis-ExtraBold.otf - Metropolis-Black.otf

Italic Styles: - Metropolis-ThinItalic.otf - Metropolis-ExtraLightItalic.otf - Metropolis-LightItalic.otf - Metropolis-RegularItalic.otf - Metropolis-MediumItalic.otf - Metropolis-SemiBoldItalic.otf - Metropolis-BoldItalic.otf - Metropolis-ExtraBoldItalic.otf - Metropolis-BlackItalic.otf

Troubleshooting

If fonts don't appear:

  1. Clear matplotlib's font cache:

    rm -rf ~/.cache/matplotlib
    

  2. Re-register fonts:

    from msuthemes import register_metropolis_fonts
    register_metropolis_fonts()
    

  3. Restart Python session

  4. Verify registration:

    from msuthemes import is_metropolis_available
    print(is_metropolis_available())
    

Font License

Metropolis is licensed under the SIL Open Font License 1.1, which allows: - Free use in personal and commercial projects - Modification and redistribution - Embedding in documents and websites

See Also