Skip to main content

Overview

The tif1.plotting module provides a suite of plotting utilities designed for Formula 1 data visualization. It maintains 100% API compatibility with the FastF1 plotting interface. It adds performance optimizations, stricter error handling, and additional features for advanced visualization workflows. This module is the primary interface for color management, style generation, and metadata lookups for F1 visualizations. Race pace comparisons, tire strategy analyses, and driver performance dashboards all use these tools. The tools ensure visual consistency and historical accuracy.

Key Features

  • Session-Aware Lookups: All team and driver metadata queries use session data loaded from the TracingInsights API. This ensures accuracy across seasons and race weekends. The module extracts driver lineups, team affiliations, and metadata from session results. No manual data entry or external configuration files are needed.
  • Season-Aware Colors: Compound color palette selection is based on the session year. The module switches between the 2018 hypersoft era and the 2019+ system. The 2018 era has 7 dry compounds with distinct colors. The 2019+ system has 3 dry compounds with pink/yellow/white colors. This ensures historical accuracy in visualizations.
  • Multiple Color Schemes: Support for three distinct color palettes:
    • default: tif1’s optimized color scheme (now aliased to fastf1)
    • fastf1: FastF1-compatible colors for drop-in replacement scenarios
    • official: Official F1 team colors extracted from liveries and branding guidelines
  • Timedelta Support: Optional matplotlib timedelta plotting via the timple library. It renders lap times, sector times, and time deltas natively on matplotlib axes. No manual conversion to seconds or string formatting is needed.
  • Fuzzy Matching: Identifier resolution with Levenshtein distance-based matching and warnings for near-matches. Accepts team names, short names, driver abbreviations, full names, and aliases. For example, “redbull”, “RBR”, and “Red Bull Racing” all resolve to the same team.
  • Type Safety: Full type hints and runtime validation for all public APIs. This gives IDE autocomplete support and early error detection during development.
  • Caching and Performance: Session-specific driver/team mappings are cached in memory. This eliminates redundant DataFrame iterations and gives O(1) lookup performance for repeated color queries.

Error Handling Philosophy

The plotting module follows strict, fail-fast error handling principles designed to surface issues immediately rather than producing incorrect visualizations:
  • Exact-match failures raise KeyError with descriptive messages indicating which identifier could not be resolved and what session data was available
  • Invalid colormap values raise ValueError immediately with a list of valid options
  • Fuzzy lookup corrections emit UserWarning messages but continue execution. The warning shows when input was auto-corrected (for example, “redbull” → “Red Bull Racing”)
  • Missing session context raises ValueError for functions that require session data (all team/driver color lookups). This prevents silent fallback to incorrect default values
This approach makes visualization code fail fast with clear error messages. Silent incorrect results are avoided, which protects data integrity in analytical workflows.

FastF1 Compatibility

The tif1.plotting module provides 100% API compatibility with the FastF1 plotting helpers. Existing visualization code migrates with zero or minimal changes. All function signatures, parameter names, return types, and behavioral semantics match the FastF1 specification. Existing scripts, notebooks, and applications can transition directly.

Design Philosophy

The compatibility layer is not a wrapper. It is a reimplementation that maintains identical external behavior with internal optimizations:
  • Signature Compatibility: All functions accept the same parameters in the same order, with identical default values
  • Return Type Compatibility: Functions return the same data types (strings, lists, dictionaries) with the same structure
  • Error Compatibility: Exceptions are raised in the same scenarios with similar error messages
  • Behavioral Compatibility: Fuzzy matching, color resolution, and style generation follow FastF1’s algorithms
The primary differences are internal. tif1 uses cached session mappings for O(1) lookups. tif1 validates inputs more strictly and gives more detailed error messages when operations fail.

Complete API Surface

The module exposes 25 public functions organized into six functional categories:

Setup and Configuration (3 functions)

  • setup_mpl - Configure matplotlib with F1-optimized defaults including color schemes, timedelta support, and visual styling
  • set_default_colormap - Set the global default color scheme (fastf1 or official) used when colormap="default" is specified
  • override_team_constants - Override team metadata (short names, colors) for specific sessions, useful for custom branding or historical corrections

Team Colors and Metadata (4 functions)

  • get_team_color - Retrieve team color hex code by identifier (name, short name, or alias)
  • get_team_name - Get full or short team name from identifier
  • get_team_name_by_driver - Look up team name from driver identifier (reverse lookup)
  • list_team_names - List all teams participating in a session

Driver Colors and Metadata (8 functions)

  • get_driver_color - Retrieve driver color (inherits from team color, following FastF1’s model where teammates share colors)
  • get_driver_abbreviation - Get three-letter driver code (for example, “VER”, “HAM”, “LEC”)
  • get_driver_name - Get full driver name from any identifier
  • get_driver_style - Generate complete matplotlib style dictionary with color, linestyle, marker, and custom properties
  • get_driver_abbreviations_by_team - List driver codes for a specific team
  • get_driver_names_by_team - List full driver names for a specific team
  • list_driver_abbreviations - List all driver codes in a session (in grid order)
  • list_driver_names - List all driver full names in a session (in grid order)

Compound (Tire) Colors (3 functions)

  • get_compound_color - Retrieve tire compound color hex code with season-aware palette selection
  • get_compound_mapping - Get complete compound-to-color mapping for a season
  • list_compounds - List all compound names available in a season (including UNKNOWN and TEST-UNKNOWN)

Mapping and Batch Operations (2 functions)

  • get_driver_color_mapping - Get all driver colors as a dictionary (abbreviation → hex color)
  • add_sorted_driver_legend - Add team-grouped, grid-ordered legend to matplotlib axes

Advanced Styling (5 functions)

  • apply_plot_style - Apply custom plot styling with background, text color, and transparency options
  • load_custom_font - Load custom fonts from file paths or URLs for typography customization
  • get_plot_config - Retrieve default plotting configuration (figure size, DPI, font sizes, spacing)
  • get_driver_abbreviations_by_team - Get driver codes for a team (also listed above)
  • get_driver_names_by_team - Get driver names for a team (also listed above)

Migration from FastF1

Migrating from FastF1 to tif1 is typically a one-line change in the import statements. The module is designed as a drop-in replacement:
The behavior and output will be identical in most cases, with tif1 providing:
  • Performance improvements: Cached session mappings eliminate redundant DataFrame iterations
  • Stricter validation: Invalid inputs are caught earlier with more descriptive error messages
  • Enhanced fuzzy matching: Improved identifier resolution with better warning messages
  • Additional features: Extra utility functions like apply_plot_style, load_custom_font, and get_plot_config

Compatibility Notes

There are a few minor behavioral differences to be aware of:
  1. Error messages: tif1 provides more detailed error messages with context about what went wrong and what data was available
  2. Warnings: Fuzzy matching warnings include the original query and the resolved value for transparency
  3. Session requirement: tif1 strictly enforces the session parameter for team/driver lookups and raises ValueError if None. FastF1 may silently return empty strings
  4. Colormap validation: tif1 validates colormap values immediately and raises ValueError for invalid options, preventing silent fallback to defaults

Matplotlib Setup

setup_mpl

Configure matplotlib with Formula 1-optimized defaults including color schemes, timedelta support, and visual styling.

Parameters

  • mpl_timedelta_support (bool, default: True) Enable timedelta plotting support via the timple library. When enabled, matplotlib can natively plot pandas.Timedelta and datetime.timedelta objects on axes. Requires the optional plotting extra to be installed.
  • color_scheme (str | None, default: None) Color scheme to apply. Valid values:
    • "fastf1" - Use FastF1’s color palette
    • "light" - tif1’s simple light theme (lightblue background, black text)
    • "default-light" - The TracingInsights v2 Fastest_Lap.py theme (lightblue background, black text, 32pt labels, hidden top/right spines)
    • "default-dark" - The TracingInsights dark-brand counterpart (#011627 background, lime text)
    • "official" - Use official F1 team colors
    • None - Use tif1’s default color scheme
  • misc_mpl_mods (bool, default: True) Apply additional matplotlib style modifications including grid styling, tick parameters, and figure aesthetics.
  • **kwargs Additional keyword arguments passed to matplotlib configuration.

Behavior

This function accepts both FastF1-style positional arguments and tif1’s keyword-only style:

Timedelta Support

For full timedelta plotting capabilities, install the optional plotting extra:
If timple is not available, tif1 will emit a runtime warning and continue with style-only setup. This allows the library to function without the plotting extra, but timedelta axes will not render correctly.

Examples

Basic setup with default settings:
FastF1 color scheme without timedelta support:
Official F1 colors with custom modifications:

Notes

  • Call setup_mpl() once at the start of the script, before creating any plots
  • The function modifies global matplotlib settings via matplotlib.rcParams
  • Timedelta support is particularly useful for lap time comparisons and race pace analysis
  • The misc_mpl_mods parameter controls grid styling, tick formatting, and other visual enhancements

Named Plot Styles

tif1 ships two named plot styles that reproduce the TracingInsights v2 chart look. default-light is extracted from Fastest_Lap.py; default-dark comes from Race_Launch_Performance_Ratings.py in the analysis repo. Use get_plot_style to read the full configuration, or pass the name to setup_mpl / any chart’s color_scheme argument.

get_plot_style

Return a copy of a registered plot style configuration. Each style config contains figure (size, dpi, constrained_layout) and fonts (title/label/annotation/footer/watermark sizes and bundled font file names). It also contains colors (background, text, grid, bar-label and ytick colors), bar, and spacing (label padding and subplots_adjust margins). The images section holds tyre/car zoom, x-offsets, and the dark style’s car_threshold of 2.5. Cars are only drawn when the x-value rating exceeds it. footer/watermark text completes the config, which mirrors the constants in the v2 scripts.
Any chart function also accepts the style name directly:

Bundled Plot Assets

The tif1.assets module ships the car artwork (all years 2018-2026), tyre compound images, and fonts inside the package. No network requests occur at plot time. The default-light/default-dark styles (and the v2 scripts) use these assets for car/tyre images.

Car images

Key helpers:
  • assets.available_car_years() / assets.available_team_codes(year) — discover bundled artwork
  • assets.car_image_path(year, code) / assets.tyre_image_path(compound) / assets.font_path(name) — package paths
  • assets.load_car_image(year, code) / assets.load_tyre_image(compound) — cached RGBA arrays
  • assets.add_car_images(ax, df, year, ...) / assets.add_tyre_images(ax, df, ...) — Fastest_Lap-style AnnotationBbox helpers (with zoom, x_offset, and threshold options)
  • assets.add_car_image_at_position(ax, x, y, year, code, ...) / assets.add_tyre_image_at_position(...) — single-image placement
  • plotting.get_team_code(identifier, session=None, *, year=None) — resolve a timing-data team name to its car code (year-aware, session-aware, fuzzy-matched)

Season-Aware Color System

The plotting module implements a season-aware color system. It adapts to the tire compound regulations and team liveries of different Formula 1 seasons.

Historical Context

Formula 1 tire compound naming and the color system have changed over the years:
  • 2018: Complex system with seven compounds (HYPERSOFT, ULTRASOFT, SUPERSOFT, SOFT, MEDIUM, HARD, SUPERHARD), each with distinct colors
  • 2019-present: Simplified three-compound system (SOFT, MEDIUM, HARD) with consistent pink/yellow/white colors, plus INTERMEDIATE and WET
The tif1 plotting module automatically selects the correct color palette based on the session year, ensuring historical accuracy in visualizations.

Color Lookup Behavior

  • Team and driver colors: Always require a session parameter to ensure accurate team identification
  • Compound colors: Can work without a session (returns modern palette) but are season-aware when a session is provided
  • Colormap selection: Three schemes available (default, fastf1, official) with validation

get_team_color

Retrieve the color hex code for a team based on the selected colormap.

Parameters

  • identifier (str) Team identifier. Accepts multiple formats:
    • Full team name: "Red Bull Racing"
    • Short name: "Red Bull"
    • Team code: "RBR"
    • Fuzzy matches: "redbull", "RedBull" (when exact_match=False)
  • session (required) A loaded tif1 Session object. Cannot be None - raises ValueError if omitted.
  • colormap (str, default: "default") Color scheme to use:
    • "default" - tif1’s optimized color palette
    • "fastf1" - FastF1-compatible colors
    • "official" - Official F1 team colors from liveries
    Invalid values raise ValueError.
  • exact_match (bool, default: False) When False, enables fuzzy matching for team identifiers. When True, requires exact string match (case-sensitive).

Returns

  • str: Hex color code (for example, "#0600ef" for Red Bull Racing)

Raises

  • ValueError: If session is None or colormap is invalid
  • KeyError: If team identifier cannot be resolved (even with fuzzy matching)

Examples

Basic team color lookup:
Comparing color schemes:
Fuzzy matching behavior:
Using in matplotlib plots:

get_compound_color

Retrieve the color hex code for a tire compound, with automatic season-aware palette selection.

Parameters

  • compound (str) Tire compound name. Valid values depend on the session year:
    • 2018: "HYPERSOFT", "ULTRASOFT", "SUPERSOFT", "SOFT", "MEDIUM", "HARD", "SUPERHARD", "INTERMEDIATE", "WET"
    • 2019+: "SOFT", "MEDIUM", "HARD", "INTERMEDIATE", "WET"
    Case-insensitive matching is supported.
  • session (optional) A loaded tif1 Session object. When provided, uses the session year to select the appropriate compound palette. When None, defaults to the modern (2019+) palette.

Returns

  • str: Hex color code for the compound (for example, "#ff0080" for HYPERSOFT in 2018)

Raises

  • KeyError: If the compound name is not valid for the session year

Examples

Modern compound colors (2019+):
Historical compound colors (2018):
Plotting tire strategy:
Without session (defaults to modern palette):

get_compound_mapping

Retrieve a complete mapping of all tire compounds to their color hex codes for a given session.

Parameters

  • session (optional) A loaded tif1 Session object. When provided, returns the season-appropriate compound palette. When None, returns the modern (2019+) palette.

Returns

  • dict[str, str]: Dictionary mapping compound names to hex color codes

Examples

Get all available compounds for a session:
Compare 2018 vs modern palettes:
Create a compound color legend:

Driver Colors and Metadata

The driver color and metadata functions give complete access to driver information extracted from session data. All functions support fuzzy matching by default and can resolve drivers from abbreviations, full names, first names, or last names.

Color Model

Following the FastF1 model, both drivers from the same team share the same team color. This design follows modern F1 broadcasting conventions. Teams are identified by a single color. Drivers are differentiated by other visual properties (linestyles, markers, helmet designs). To distinguish between teammates in visualizations, use the get_driver_style function. It assigns different linestyles and markers based on grid position within the team.

get_driver_color

Retrieve the color hex code for a driver. Since drivers inherit their team’s color, this function internally resolves the driver to their team and returns the team color.

Parameters

  • identifier (str, required) Driver identifier. Accepts multiple formats:
    • Three-letter abbreviation: "VER", "HAM", "LEC"
    • Full name: "Max Verstappen", "Lewis Hamilton"
    • First name only: "Max", "Lewis" (may be ambiguous if multiple drivers share the same first name)
    • Last name only: "Verstappen", "Hamilton"
    • Fuzzy matches: "verstappen", "HAMILTON", "max" (when exact_match=False)
  • session (required) A loaded tif1 Session object. Cannot be None - raises ValueError if omitted. The session must have been loaded with session.load() to populate driver and team data.
  • colormap (str, default: "default") Color scheme to use:
    • "default" - Resolves to the global default colormap (set via set_default_colormap, initially "fastf1")
    • "fastf1" - FastF1-compatible colors optimized for dark backgrounds
    • "official" - Official F1 team colors from liveries and branding
    Invalid values raise ValueError with a list of valid options.
  • exact_match (bool, default: False) When False, enables fuzzy matching using Levenshtein distance. When True, requires exact string match (case-sensitive) against driver abbreviation, full name, first name, or last name.

Returns

  • str: Hex color code (for example, "#0600ef" for Red Bull drivers in the fastf1 colormap)

Raises

  • ValueError: If session is None or colormap is invalid
  • KeyError: If driver identifier cannot be resolved (even with fuzzy matching), or if session has no driver data

Behavior Details

  1. Driver Resolution: The function first resolves the identifier to a driver using the session’s driver/team mapping
  2. Team Lookup: Once the driver is identified, their team affiliation is retrieved
  3. Color Selection: The team’s color is returned based on the selected colormap
  4. Fuzzy Matching: If exact match fails, Levenshtein distance finds the closest match. A warning is emitted if the match is not exact

Examples

Basic driver color lookup:
Different identifier formats:
Comparing colormaps:
Fuzzy matching with warnings:
Using in matplotlib plots:
Error handling:

get_driver_style

Generate a complete matplotlib style dictionary for a driver, including color, linestyle, marker, and custom properties. This is the primary function for creating visually distinct styles for teammates and different drivers.

Parameters

  • identifier (str, required) Driver identifier (same formats as get_driver_color)
  • style (str | Sequence[str] | Sequence[dict[str, Any]], required) Style specification. Three formats are supported:
    1. Single string: A single style property name (for example, "color", "linestyle", "marker")
    2. List of strings: Multiple style property names (for example, ["color", "linestyle", "marker"])
    3. List of dictionaries: Custom style dictionaries per driver, indexed by team position (for example, [{"color": "auto", "linewidth": 2}, {"color": "auto", "linewidth": 3}])
    Valid style property names:
    • "color" - Driver/team color
    • "linestyle" - Line style (rotates through: "solid", "dashed", "dashdot", "dotted")
    • "marker" - Marker style (rotates through: "x", "o", "^", "D")
    • Any matplotlib color keyword: "facecolor", "edgecolor", "markerfacecolor", "markeredgecolor", etc.
  • session (required) A loaded tif1 Session object
  • colormap (str, default: "default") Color scheme to use (same as get_driver_color)
  • additional_color_kws (Sequence[str], default: ()) Additional keyword arguments that should be treated as color properties. Useful for custom matplotlib artists with non-standard color parameters.
  • exact_match (bool, default: False) Enable exact matching for driver identifier resolution

Returns

  • dict[str, Any]: Dictionary of matplotlib style properties that can be unpacked into plotting functions

Raises

  • ValueError: If style is empty, has invalid format, or contains unsupported property names
  • KeyError: If driver cannot be resolved

Behavior Details

Team Position Rotation: Drivers within the same team are assigned different linestyles and markers. The assignment is based on grid position (order in session results). The first driver (typically the one who qualified higher) gets the first style in the rotation. The second driver gets the second style, and so on. Linestyle Rotation: ["solid", "dashed", "dashdot", "dotted"] Marker Rotation: ["x", "o", "^", "D"] Auto Color Replacement: In custom style dictionaries (format 3), a property with value "auto" becomes the driver’s team color. This allows custom styles that still respect team colors.

Examples

Basic style generation:
Teammate differentiation:
Using in matplotlib plots:
Custom style dictionaries:
Additional color keywords:

get_driver_abbreviation

Get the three-letter driver abbreviation (for example, “VER”, “HAM”, “LEC”) from any driver identifier.

Parameters

  • identifier (str, required) - Driver identifier (full name, abbreviation, first/last name)
  • session (required) - Loaded tif1 Session object
  • exact_match (bool, default: False) - Enable exact matching

Returns

  • str: Three-letter driver abbreviation (for example, "VER")

Examples

get_driver_name

Get the full driver name from any driver identifier.

Parameters

  • identifier (str, required) - Driver identifier
  • session (required) - Loaded tif1 Session object
  • exact_match (bool, default: False) - Enable exact matching

Returns

  • str: Full driver name (for example, "Max Verstappen")

Examples

list_driver_abbreviations

Get a list of all driver abbreviations in the session, ordered by grid position (as they appear in session results).

Parameters

  • session (required) - Loaded tif1 Session object

Returns

  • list[str]: List of three-letter driver abbreviations in grid order

Examples

list_driver_names

Get a list of all driver full names in the session, ordered by grid position.

Parameters

  • session (required) - Loaded tif1 Session object

Returns

  • list[str]: List of full driver names in grid order

Examples

get_driver_abbreviations_by_team

Get a list of driver abbreviations for a specific team.

Parameters

  • identifier (str, required) - Team identifier
  • session (required) - Loaded tif1 Session object
  • exact_match (bool, default: False) - Enable exact matching for team resolution

Returns

  • list[str]: List of driver abbreviations for the team (typically 2 drivers)

Examples

get_driver_names_by_team

Get a list of full driver names for a specific team.

Parameters

  • identifier (str, required) - Team identifier
  • session (required) - Loaded tif1 Session object
  • exact_match (bool, default: False) - Enable exact matching for team resolution

Returns

  • list[str]: List of full driver names for the team

Examples

get_driver_color_mapping

Get a complete mapping from driver abbreviations to color hex codes for all drivers in a session. This is useful for batch operations that look up colors for multiple drivers efficiently.

Parameters

  • session (required) - Loaded tif1 Session object
  • colormap (str, default: "default") - Color scheme to use

Returns

  • dict[str, str]: Dictionary mapping driver abbreviations to hex color codes

Examples

legend and overrides

add_sorted_driver_legend

This groups drivers by team and keeps teammates in the same order used for style selection. Unresolved legend labels are preserved and appended after all resolved driver labels.

set_default_colormap

override_team_constants

Overrides are session-scoped and use exact-match semantics.

examples

Last modified on September 3, 2026