Overview
Thetif1.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 (initiallyfastf1; change it withset_default_colormap)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 substring and
rapidfuzzsimilarity 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: useget_team_codefor 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
KeyErrorwith a message that names the identifier that could not be resolved - Invalid colormap values raise
ValueErrorimmediately - Fuzzy lookup corrections emit
UserWarningmessages but continue execution. The warning shows when input was auto-corrected (for example, “Ferari” → “Ferrari”) - Missing session context raises
ValueErrorfor the color lookups that require session data (get_team_color,get_driver_color,get_driver_style, andoverride_team_constants). This prevents silent fallback to incorrect default values
FastF1 Compatibility
Thetif1.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.
sessiondefaults toNonewhere FastF1 requires it - Return Type Compatibility: Functions return the same data types (strings, lists, dictionaries) with the same structure
- Error Compatibility: Failed lookups raise
KeyErrorand invalid arguments raiseValueError - Behavioral Compatibility: Fuzzy matching, color resolution, and style generation follow FastF1’s algorithms
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 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 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 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 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 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_plot_style- Return a copy of a named plot style (lightordark)
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 seasonteam_color_mapping- Get the TracingInsights v2 chart palette for a season
Migration from FastF1
Migrating from FastF1 to tif1 typically replaces thefastf1 imports and prefixes with tif1:
- Stricter validation: An unknown
color_schemeraisesValueError. A driver name on a session without driver names raisesKeyErrorinstead of a wrong fuzzy match - More themes:
setup_mplalso accepts thedarkandlightcolor schemes - Additional features: Extra utility functions like
apply_plot_style,load_custom_font,get_plot_config, andget_team_code
Compatibility Notes
There are a few minor behavioral differences to be aware of:- Warnings: Fuzzy matching warnings include the original query and the resolved value for transparency
- Session requirement: tif1 requires the session parameter for team and driver color lookups and raises
ValueErrorif it isNone. Name lookups without a session return an empty string. The driver and team list helpers return an empty list, andget_driver_color_mappingreturns an empty dict - Colormap validation: tif1 validates colormap values immediately and raises
ValueErrorfor invalid options, preventing silent fallback to defaults - Deprecated FastF1 helpers: tif1 does not provide FastF1’s deprecated
driver_color,team_color, andlapnumber_axisfunctions or color constants such asDRIVER_COLORS
Matplotlib Setup
setup_mpl
Parameters
-
mpl_timedelta_support(bool | str, default:True) Enable timedelta plotting support via thetimplelibrary. When enabled, matplotlib can natively plotpandas.Timedeltaanddatetime.timedeltaobjects on axes.timpleis installed withtif1. For backward compatibility, a string in this position is read ascolor_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 (#011627background, lime text, hidden top/right spines, no y tick marks)"light"- The TracingInsights v2Fastest_Lap.pytheme (lightblue background, black text, hidden top/right spines, no y tick marks)None- Apply no theme and leave the matplotlib colors unchanged
darkandlightnames (tif1 0.8) still work and map todarkandlightwith aDeprecationWarning. Thedarkandlightschemes 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 32ptlabel_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 withset_default_colormap("official")or thecolormap=argument. Any value other than the four schemes above (orNone) raisesValueError. -
misc_mpl_mods(bool, default:True) Apply the color scheme. WhenFalse,setup_mplonly sets up timedelta support and changes no style settings. -
**kwargsbackgroundandtext_coloroverride the colors of thelightanddefault-*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: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 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
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 light/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, 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
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 colormap values 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" - Fuzzy matches:
"redbull","RedBull"(whenexact_match=False)
"RBR"are not accepted: fuzzy matching can resolve them to a different team. - Full team name:
-
session(required) A loaded tif1 Session object. Cannot beNone- raisesValueErrorif omitted. -
colormap(str, default:"default") Color scheme to use:"default"- The global default colormap (set viaset_default_colormap, initially"fastf1")"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, 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: 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"
"UNKNOWN"and"TEST-UNKNOWN". Case-insensitive matching is supported. - 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,"#feb1c1"for HYPERSOFT in 2018)
UNKNOWN color ("#00ffff").
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. 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 theget_driver_style function. It assigns different linestyles and markers based on the classification order 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"official"- Official F1 team colors from liveries and branding
ValueError. -
exact_match(bool, default:False) WhenFalse, enables fuzzy matching. WhenTrue, 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: 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,
fuzzy_matcherfinds 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 raisesKeyError
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")- 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
ValueError. - 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 names. A list of dictionaries with fewer entries than the driver’s position in the team also raisesKeyError: 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 ofsession.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: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
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
Parameters
session(required) - Loaded tif1 Session object
Returns
list[str]: List of full driver names in classification 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
Examples
Legend and overrides
add_sorted_driver_legend
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.