Skip to main content

Overview

The tif1.plotting module provides a suite of plotting utilities designed for Formula 1 data visualization. It reimplements the FastF1 plotting helpers with the same function names and parameters. It adds 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 red/yellow/white colors. This ensures historical accuracy in visualizations.
  • Multiple Color Schemes: Support for three distinct color palettes:
    • default: the global default colormap (initially fastf1; change it with set_default_colormap)
    • 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 substring and rapidfuzz similarity matching (tif1.fuzzy.fuzzy_matcher) and warnings for near-matches. Accepts team names, short names, driver abbreviations, full names, and aliases. For example, “redbull”, “red bull”, and “Red Bull Racing” all resolve to the same team. Car codes such as “RBR” are not team aliases: use get_team_code for car codes.
  • Type Safety: Type hints on the color, name, and style lookup functions. Invalid colormap, color scheme, and style arguments raise ValueError.
  • Caching and Performance: Session-specific driver/team mappings are built once per session and cached in memory. Repeated color queries do not read the session DataFrames again.

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 a message that names the identifier that could not be resolved
  • Invalid colormap values raise ValueError immediately
  • Fuzzy lookup corrections emit UserWarning messages but continue execution. The warning shows when input was auto-corrected (for example, “Ferari” → “Ferrari”)
  • Missing session context raises ValueError for the color lookups that require session data (get_team_color, get_driver_color, get_driver_style, and override_team_constants). 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 reimplements the FastF1 plotting helpers. The shared functions keep the FastF1 names, parameter names, parameter order, and return types. Most visualization code migrates with an import change. The compatibility notes list the differences.

Design Philosophy

The compatibility layer is not a wrapper. It is a reimplementation that keeps the FastF1 external behavior for the shared functions:
  • Signature Compatibility: The shared functions accept the same parameters in the same order. session defaults to None where FastF1 requires it
  • Return Type Compatibility: Functions return the same data types (strings, lists, dictionaries) with the same structure
  • Error Compatibility: Failed lookups raise KeyError and invalid arguments raise ValueError
  • Behavioral Compatibility: Fuzzy matching, color resolution, and style generation follow FastF1’s algorithms
tif1 builds one cached driver/team mapping per session and validates inputs more strictly.

Complete API Surface

The module exposes 27 public functions organized into seven 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 classification order)
  • list_driver_names - List all driver full names in a session (in classification 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 a team-grouped legend in classification order to matplotlib axes

Advanced Styling (4 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_plot_style - Return a copy of a named plot style (light or dark)

Car Codes and Chart Palette (3 functions)

  • get_team_code - Resolve a team name to its car image code (for example, "RBR")
  • team_code_mapping - Get the team name to car code mapping for a season
  • team_color_mapping - Get the TracingInsights v2 chart palette for a season

Migration from FastF1

Migrating from FastF1 to tif1 typically replaces the fastf1 imports and prefixes with tif1:
The behavior and output are identical in most cases, with tif1 providing:
  • Stricter validation: An unknown color_scheme raises ValueError. A driver name on a session without driver names raises KeyError instead of a wrong fuzzy match
  • More themes: setup_mpl also accepts the dark and light color schemes
  • Additional features: Extra utility functions like apply_plot_style, load_custom_font, get_plot_config, and get_team_code

Compatibility Notes

There are a few minor behavioral differences to be aware of:
  1. Warnings: Fuzzy matching warnings include the original query and the resolved value for transparency
  2. Session requirement: tif1 requires the session parameter for team and driver color lookups and raises ValueError if it is None. Name lookups without a session return an empty string. The driver and team list helpers return an empty list, and get_driver_color_mapping returns an empty dict
  3. Colormap validation: tif1 validates colormap values immediately and raises ValueError for invalid options, preventing silent fallback to defaults
  4. Deprecated FastF1 helpers: tif1 does not provide FastF1’s deprecated driver_color, team_color, and lapnumber_axis functions or color constants such as DRIVER_COLORS

Matplotlib Setup

setup_mpl

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

Parameters

  • mpl_timedelta_support (bool | str, default: True) Enable timedelta plotting support via the timple library. When enabled, matplotlib can natively plot pandas.Timedelta and datetime.timedelta objects on axes. timple is installed with tif1. For backward compatibility, a string in this position is read as color_scheme, and timedelta support is then off.
  • color_scheme (str | None, default: None) Color scheme to apply. Valid values:
    • "fastf1" - Use FastF1’s color palette
    • "dark" - The TracingInsights dark-brand theme (#011627 background, lime text, hidden top/right spines, no y tick marks)
    • "light" - The TracingInsights v2 Fastest_Lap.py theme (lightblue background, black text, hidden top/right spines, no y tick marks)
    • None - Apply no theme and leave the matplotlib colors unchanged
    The deprecated dark and light names (tif1 0.8) still work and map to dark and light with a DeprecationWarning. The dark and light schemes do not force the v2 scripts’ 32pt tick, legend and axis-label fonts globally. Those sizes were tuned for 20x20 inch canvases and are too large for the 10x8 inch charts. The 20x20 race-launch chart still draws its labels at the style’s 32pt label_size. Applying any named scheme first resets every rcParams key the schemes manage, so themes never leak into one another. "official" is not a theme: it is a colormap for color lookups. Select it with set_default_colormap("official") or the colormap= argument. Any value other than the four schemes above (or None) raises ValueError.
  • misc_mpl_mods (bool, default: True) Apply the color scheme. When False, setup_mpl only sets up timedelta support and changes no style settings.
  • **kwargs background and text_color override the colors of the light and default-* schemes. Other keys are ignored.

Behavior

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

Timedelta Support

timple is a required dependency of tif1, so timedelta plotting works out of the box. If timple has been removed from the environment, tif1 emits a RuntimeWarning and continues with style-only setup. Timedelta axes do not render correctly until timple is reinstalled.

Examples

Basic setup with default settings:
FastF1 color scheme without timedelta support:
Official F1 team colors on the fastf1 theme:

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 whether the color scheme is applied

Named Plot Styles

tif1 ships two named plot styles that reproduce the TracingInsights v2 chart look. light is extracted from Fastest_Lap.py; 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 light/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, exact_match=False) — resolve a timing-data team name to its car code (year-aware, and fuzzy-matched when a session is given)

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 red/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 colormap values 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"
    • Fuzzy matches: "redbull", "RedBull" (when exact_match=False)
    Car codes such as "RBR" are not accepted: fuzzy matching can resolve them to a different team.
  • session (required) A loaded tif1 Session object. Cannot be None - raises ValueError if omitted.
  • colormap (str, default: "default") Color scheme to use:
    • "default" - The global default colormap (set via set_default_colormap, initially "fastf1")
    • "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, the identifier must equal a team name or alias. Case and accents are still ignored, but no fuzzy correction occurs.

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"
    Both palettes also contain "UNKNOWN" and "TEST-UNKNOWN". 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, "#feb1c1" for HYPERSOFT in 2018)
The function does not raise for an unknown compound. A compound that is not in the season palette returns the UNKNOWN color ("#00ffff").

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. Teams are identified by a single color. Drivers are differentiated by other visual properties, such as linestyles and markers. To distinguish between teammates in visualizations, use the get_driver_style function. It assigns different linestyles and markers based on the classification order 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
    • "official" - Official F1 team colors from liveries and branding
    Invalid values raise ValueError.
  • exact_match (bool, default: False) When False, enables fuzzy matching. When True, the identifier must equal the driver abbreviation, full name, first name, or last name. Case and accents are still ignored, but no fuzzy correction occurs.
Name identifiers need driver names in the session data. Some sessions, for example the 2024 Belgian Grand Prix, carry only the 3-letter codes. On those sessions, a name such as "Hamilton" is not fuzzy-matched to a wrong driver. It raises KeyError (“this session has no driver names, use the three-letter abbreviation”). Use the 3-letter codes when session.results["FullName"] is empty.

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, fuzzy_matcher finds the closest match. A warning is emitted if the match is not exact. An unknown identifier is not an error in this mode: it resolves to the closest driver. The exception is a session without driver names (see the note above), which raises KeyError

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")
    • A matplotlib color keyword: "color", "c", "colors", "gapcolor", "ecolor", "facecolor", "fc", "facecolors"
    • An edge or marker color keyword: "edgecolor", "ec", "edgecolors", "markerfacecolor", "mfc", "markerfacecoloralt", "mfcalt", "markeredgecolor", "mec"
    • Any name passed in additional_color_kws
    Other names raise ValueError.
  • 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. A list of dictionaries with fewer entries than the driver’s position in the team also raises
  • KeyError: If driver cannot be resolved

Behavior Details

Team Position Rotation: Drivers within the same team are assigned different linestyles and markers. The assignment follows the order of session.results, which is the classification order. The better-classified teammate 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 color property with value "auto" becomes the driver’s team color. The replaced keys are color, facecolor, edgecolor, markerfacecolor, markeredgecolor, any name in additional_color_kws, and the same keys inside nested dictionaries. 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, in classification order (as they appear in session.results).

Parameters

  • session (required) - Loaded tif1 Session object

Returns

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

Examples

list_driver_names

Get a list of all driver full names in the session, in classification order.

Parameters

  • session (required) - Loaded tif1 Session object

Returns

  • list[str]: List of full driver names in classification 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

Add a legend to ax and return the matplotlib Legend. This groups drivers by team and keeps teammates in the same order used for style selection. Teams appear in the order of their best-classified driver. 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 October 28, 2026