Overview
Thetif1.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 tofastf1)fastf1: FastF1-compatible colors for drop-in replacement scenariosofficial: Official F1 team colors extracted from liveries and branding guidelines
-
Timedelta Support: Optional matplotlib timedelta plotting via the
timplelibrary. 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
KeyErrorwith descriptive messages indicating which identifier could not be resolved and what session data was available - Invalid colormap values raise
ValueErrorimmediately with a list of valid options - Fuzzy lookup corrections emit
UserWarningmessages but continue execution. The warning shows when input was auto-corrected (for example, “redbull” → “Red Bull Racing”) - Missing session context raises
ValueErrorfor functions that require session data (all team/driver color lookups). This prevents silent fallback to incorrect default values
FastF1 Compatibility
Thetif1.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
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 stylingset_default_colormap- Set the global default color scheme (fastf1orofficial) used whencolormap="default"is specifiedoverride_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 identifierget_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 identifierget_driver_style- Generate complete matplotlib style dictionary with color, linestyle, marker, and custom propertiesget_driver_abbreviations_by_team- List driver codes for a specific teamget_driver_names_by_team- List full driver names for a specific teamlist_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 selectionget_compound_mapping- Get complete compound-to-color mapping for a seasonlist_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 optionsload_custom_font- Load custom fonts from file paths or URLs for typography customizationget_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:- 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, andget_plot_config
Compatibility Notes
There are a few minor behavioral differences to be aware of:- Error messages: tif1 provides more detailed error messages with context about what went wrong and what data was available
- Warnings: Fuzzy matching warnings include the original query and the resolved value for transparency
- Session requirement: tif1 strictly enforces the session parameter for team/driver lookups and raises
ValueErrorifNone. FastF1 may silently return empty strings - Colormap validation: tif1 validates colormap values immediately and raises
ValueErrorfor invalid options, preventing silent fallback to defaults
Matplotlib Setup
setup_mpl
Parameters
-
mpl_timedelta_support(bool, default:True) Enable timedelta plotting support via thetimplelibrary. When enabled, matplotlib can natively plotpandas.Timedeltaanddatetime.timedeltaobjects on axes. Requires the optionalplottingextra 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 v2Fastest_Lap.pytheme (lightblue background, black text, 32pt labels, hidden top/right spines)"default-dark"- The TracingInsights dark-brand counterpart (#011627background, lime text)"official"- Use official F1 team colorsNone- 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. -
**kwargsAdditional 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: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: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_modsparameter 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
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.
Bundled Plot Assets
Thetif1.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
assets.available_car_years()/assets.available_team_codes(year)— discover bundled artworkassets.car_image_path(year, code)/assets.tyre_image_path(compound)/assets.font_path(name)— package pathsassets.load_car_image(year, code)/assets.load_tyre_image(compound)— cached RGBA arraysassets.add_car_images(ax, df, year, ...)/assets.add_tyre_images(ax, df, ...)— Fastest_Lap-styleAnnotationBboxhelpers (withzoom,x_offset, andthresholdoptions)assets.add_car_image_at_position(ax, x, y, year, code, ...)/assets.add_tyre_image_at_position(...)— single-image placementplotting.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
Color Lookup Behavior
- Team and driver colors: Always require a
sessionparameter 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
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"(whenexact_match=False)
- Full team name:
-
session(required) A loaded tif1 Session object. Cannot beNone- raisesValueErrorif 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
ValueError. -
exact_match(bool, default:False) WhenFalse, enables fuzzy matching for team identifiers. WhenTrue, requires exact string match (case-sensitive).
Returns
str: Hex color code (for example,"#0600ef"for Red Bull Racing)
Raises
ValueError: IfsessionisNoneorcolormapis invalidKeyError: If team identifier cannot be resolved (even with fuzzy matching)
Examples
Basic team color lookup:get_compound_color
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"
- 2018:
-
session(optional) A loaded tif1 Session object. When provided, uses the session year to select the appropriate compound palette. WhenNone, 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+):get_compound_mapping
Parameters
session(optional) A loaded tif1 Session object. When provided, returns the season-appropriate compound palette. WhenNone, 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: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 theget_driver_style function. It assigns different linestyles and markers based on grid position within the team.
get_driver_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"(whenexact_match=False)
- Three-letter abbreviation:
-
session(required) A loaded tif1 Session object. Cannot beNone- raisesValueErrorif omitted. The session must have been loaded withsession.load()to populate driver and team data. -
colormap(str, default:"default") Color scheme to use:"default"- Resolves to the global default colormap (set viaset_default_colormap, initially"fastf1")"fastf1"- FastF1-compatible colors optimized for dark backgrounds"official"- Official F1 team colors from liveries and branding
ValueErrorwith a list of valid options. -
exact_match(bool, default:False) WhenFalse, enables fuzzy matching using Levenshtein distance. WhenTrue, 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: IfsessionisNoneorcolormapis invalidKeyError: If driver identifier cannot be resolved (even with fuzzy matching), or if session has no driver data
Behavior Details
- Driver Resolution: The function first resolves the identifier to a driver using the session’s driver/team mapping
- Team Lookup: Once the driver is identified, their team affiliation is retrieved
- Color Selection: The team’s color is returned based on the selected colormap
- 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:get_driver_style
Parameters
-
identifier(str, required) Driver identifier (same formats asget_driver_color) -
style(str | Sequence[str] | Sequence[dict[str, Any]], required) Style specification. Three formats are supported:- Single string: A single style property name (for example,
"color","linestyle","marker") - List of strings: Multiple style property names (for example,
["color", "linestyle", "marker"]) - List of dictionaries: Custom style dictionaries per driver, indexed by team position (for example,
[{"color": "auto", "linewidth": 2}, {"color": "auto", "linewidth": 3}])
"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.
- Single string: A single style property name (for example,
-
session(required) A loaded tif1 Session object -
colormap(str, default:"default") Color scheme to use (same asget_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: Ifstyleis empty, has invalid format, or contains unsupported property namesKeyError: 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:get_driver_abbreviation
Parameters
identifier(str, required) - Driver identifier (full name, abbreviation, first/last name)session(required) - Loaded tif1 Session objectexact_match(bool, default:False) - Enable exact matching
Returns
str: Three-letter driver abbreviation (for example,"VER")
Examples
get_driver_name
Parameters
identifier(str, required) - Driver identifiersession(required) - Loaded tif1 Session objectexact_match(bool, default:False) - Enable exact matching
Returns
str: Full driver name (for example,"Max Verstappen")
Examples
list_driver_abbreviations
Parameters
session(required) - Loaded tif1 Session object
Returns
list[str]: List of three-letter driver abbreviations in grid order
Examples
list_driver_names
Parameters
session(required) - Loaded tif1 Session object
Returns
list[str]: List of full driver names in grid order
Examples
get_driver_abbreviations_by_team
Parameters
identifier(str, required) - Team identifiersession(required) - Loaded tif1 Session objectexact_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
Parameters
identifier(str, required) - Team identifiersession(required) - Loaded tif1 Session objectexact_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
Parameters
session(required) - Loaded tif1 Session objectcolormap(str, default:"default") - Color scheme to use
Returns
dict[str, str]: Dictionary mapping driver abbreviations to hex color codes