Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
theOehrly committed Feb 18, 2024
1 parent b7fe807 commit a1ed97c
Show file tree
Hide file tree
Showing 15 changed files with 1,237 additions and 241 deletions.
2 changes: 1 addition & 1 deletion docs/changelog/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ Release Notes

Looking for :ref:`previous-release-notes`?

.. include:: v3.2.x.rst
.. include:: v3.3.x.rst

1 change: 1 addition & 0 deletions docs/changelog/previous.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Release Notes for Older Versions
.. toctree::
:maxdepth: 1

v3.2.x
v3.1.x
v3.0.x
v2.3.2
Expand Down
37 changes: 37 additions & 0 deletions docs/changelog/v3.3.x.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

What's new in v3.3.0
--------------------

(released dd/mm/yyyy)


New Features
^^^^^^^^^^^^



Bug Fixes
^^^^^^^^^


Deprecations
^^^^^^^^^^^^

- The following module level properties of :mod:`fastf1.plotting` have been
deprecated:
:attr:`~fastf1.plotting.COMPOUND_COLORS`,
:attr:`~fastf1.plotting.DRIVER_TRANSLATE`,
:attr:`~fastf1.plotting.TEAM_COLORS`,
:attr:`~fastf1.plotting.TEAM_TRANSLATE`,
:attr:`~fastf1.plotting.COLOR_PALETTE`


- The following functions in :mod:`fastf1.plotting` have been deprecated:
:func:`~fastf1.plotting.driver_color`,
:func:`~fastf1.plotting.team_color`


Removals
^^^^^^^^

- ``fastf1.plotting.lapnumber_axis`` has been removed
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
(r'py:.*', r'pandas\..*'),
(r'py:.*', r'pd\..*'),
(r'py:.*', r'numpy\..*'),
(r'py:.*', r'matplotlib\..*'),
(r'py:mod', r'logging'),
(r'py:class', r'logging.Logger'),
]
Expand Down
27 changes: 27 additions & 0 deletions docs/plotting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,31 @@ Plotting - :mod:`fastf1.plotting`

.. automodule:: fastf1.plotting
:members:
add_sorted_driver_legend,
get_compound_color,
get_driver_abbreviation,
get_driver_abbreviations_by_team,
get_driver_color,
get_driver_name,
get_driver_names_by_team,
get_driver_style,
get_team_color,
get_team_name,
get_team_name_by_driver,
setup_mpl,
driver_color,
team_color
:show-inheritance:

Deprecated Attributes
---------------------

The following module-level attributes are deprecated since version 3.3.0 and
will be removed in a future release.

.. automodule:: fastf1.plotting
:no-index:
:members:
:exclude-members:
get_compound_color
:show-inheritance:
104 changes: 104 additions & 0 deletions examples/plot_driver_styling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""Driver specific plot styling
===============================
Create some plots and show the usage of ``fastf1.plotting.get_driver_style``.
"""

from matplotlib import pyplot as plt

import fastf1
from fastf1 import plotting


plotting.setup_mpl()


###############################################################################
# Load the race session.

race = fastf1.get_session(2023, "Azerbaijan", 'R')
race.load()

###############################################################################
# Basic driver-specific plot styling
# ----------------------------------
# Plot all the laps for Hamilton, Russel, Perez and Verstappen.
# Filter out slow laps as they distort the graph axis.
# Note: as LapTime is represented by timedelta, calling ``setup_mpl`` earlier
# is required.

fig, ax = plt.subplots(figsize=(8, 5))

for driver in ('HAM', 'PER', 'VER', 'RUS'):
laps = race.laps.pick_driver(driver).pick_quicklaps().reset_index()
style = plotting.get_driver_style(identifier=driver,
style=['color', 'linestyle'],
session=race)
ax.plot(laps['LapTime'], **style, label=driver)

# add axis labels and a legend
ax.set_xlabel("Lap Number")
ax.set_ylabel("Lap Time")
ax.legend()

###############################################################################
# Sorting the legend
# ------------------
# That plot looks pretty good already, but the order of the labels in the
# legend is slightly chaotic. Instead of trying to order the labels manually,
# use :func:`fastf1.plotting.add_sorted_driver_legend`.
# Let's create the exact same plot again, but this time with a sorted legend
# which means, we only change the very last function call.

fig, ax = plt.subplots(figsize=(8, 5))

for driver in ('HAM', 'PER', 'VER', 'RUS'):
laps = race.laps.pick_driver(driver).pick_quicklaps().reset_index()
style = plotting.get_driver_style(identifier=driver,
style=['color', 'linestyle'],
session=race)
ax.plot(laps['LapTime'], **style, label=driver)

# add axis labels and a legend
ax.set_xlabel("Lap Number")
ax.set_ylabel("Lap Time")
plotting.add_sorted_driver_legend(ax, session=race)

###############################################################################
# Creating fully custom styles
# ----------------------------
# If you want to fully customize the plot style, you can define your own
# styling variants.
#
# Note that the value ``'auto'`` is treated as a magic keyword when used in
# combination with a color. It will be replaced with the team color.
#
# We define two styles, one for the first driver and one for the second driver
# in any team.
#
# The plot that is generated here isn't intended to be very readable, but it
# shows how you can customize any plot styling parameter.

my_styles = [
# style for each first driver
{'color': 'auto', 'linestyle': 'solid', 'linewidth': 5, 'alpha': 0.3},
# style for each second driver
{'color': 'auto', 'linestyle': 'solid', 'linewidth': 1, 'alpha': 0.7}
]

fig, ax = plt.subplots(figsize=(8, 5))

for driver in ('HAM', 'PER', 'VER', 'RUS'):
laps = race.laps.pick_driver(driver).pick_quicklaps().reset_index()

# here, we now use ``style=my_style`` to use the custom styling
style = plotting.get_driver_style(identifier=driver,
style=my_styles,
session=race)

ax.plot(laps['LapTime'], **style, label=driver)

# add axis labels and a legend
ax.set_xlabel("Lap Number")
ax.set_ylabel("Lap Time")
plotting.add_sorted_driver_legend(ax, session=race)
6 changes: 4 additions & 2 deletions examples/plot_position_changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,12 @@
drv_laps = session.laps.pick_driver(drv)

abb = drv_laps['Driver'].iloc[0]
color = fastf1.plotting.driver_color(abb)
style = fastf1.plotting.get_driver_style(identifier=abb,
style=['color', 'linestyle'],
session=session)

ax.plot(drv_laps['LapNumber'], drv_laps['Position'],
label=abb, color=color)
label=abb, **style)
# sphinx_gallery_defer_figures

##############################################################################
Expand Down
3 changes: 0 additions & 3 deletions fastf1/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2995,9 +2995,6 @@ def pick_team(self, name: str) -> "Laps":
mercedes = session_laps.pick_team('Mercedes')
alfa_romeo = session_laps.pick_team('Alfa Romeo')
Have a look to :attr:`fastf1.plotting.TEAM_COLORS` for a quick
reference on team names.
Args:
name (str): Team name
Expand Down
124 changes: 124 additions & 0 deletions fastf1/plotting/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import warnings
from functools import cached_property
from typing import (
Dict,
List
)

from fastf1.core import Session
from fastf1.plotting._constants import LEGACY_TEAM_TRANSLATE as _LGT
from fastf1.plotting._constants import Constants as _Constants
from fastf1.plotting._constants.base import Colormaps as _Colormaps
from fastf1.plotting._constants.base import Compounds as _Compounds
from fastf1.plotting._drivers import ( # noqa: F401
_get_driver_team_mapping,
add_sorted_driver_legend,
get_driver_abbreviation,
get_driver_abbreviations_by_team,
get_driver_color,
get_driver_name,
get_driver_names_by_team,
get_driver_style,
get_team_color,
get_team_name,
get_team_name_by_driver
)
from fastf1.plotting._plotting import ( # noqa: F401
_COLOR_PALETTE,
driver_color,
setup_mpl,
team_color
)


def __getattr__(name):
if name in ('COMPOUND_COLORS', 'DRIVER_TRANSLATE',
'TEAM_COLORS', 'TEAM_TRANSLATE', 'COLOR_PALETTE'):
warnings.warn(f"{name} is deprecated and will be removed in a future"
f"version.", FutureWarning)
return globals()[f"_DEPR_{name}"]

raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


_DEPR_COMPOUND_COLORS: Dict[str, str] = {
str(key.value): val for key, val
in _Constants['2024'].CompoundColors.items()
}
COMPOUND_COLORS: Dict[str, str]
"""
Mapping of tyre compound names to compound colors (hex color codes).
(current season only)
.. deprecated:: 3.3.0
The ``COMPOUND_COLORS`` dictionary is deprecated and will be removed in a
future version. Use :func:`~fastf1.plotting.get_compound_color` instead.
"""

@cached_property
def _DEPR_DRIVER_TRANSLATE() -> Dict[str, str]:
dtm = _get_driver_team_mapping(session=None)
abb_to_name = dtm.abbreviation_to_name
for abb in abb_to_name.keys():
abb_to_name[abb] = abb_to_name[abb].lower()
return abb_to_name


DRIVER_TRANSLATE: Dict[str, str]
"""
Mapping of driver names to theirs respective abbreviations.
.. deprecated:: 3.3.0
The ``DRIVER_TRANSLATE`` dictionary is deprecated and will be removed in a
future version. Use :func:`~fastf1.plotting.get_driver_name` instead.
"""

_DEPR_TEAM_COLORS: Dict[str, str] = {
str(key.value): val for key, val
in _Constants['2024'].Colormaps[_Colormaps.Default].items()
}
TEAM_COLORS: Dict[str, str]
"""
Mapping of team names to team colors (hex color codes).
(current season only)
.. deprecated:: 3.3.0
The ``TEAM_COLORS`` dictionary is deprecated and will be removed in a
future version. Use :func:`~fastf1.plotting.get_team_color` instead.
"""

_DEPR_TEAM_TRANSLATE: Dict[str, str] = {
str(key): val for key, val in _LGT.items()
}
TEAM_TRANSLATE: Dict[str, str]
"""
Mapping of team names to theirs respective abbreviations.
.. deprecated:: 3.3.0
The ``TEAM_TRANSLATE`` dictionary is deprecated and will be removed in a
future version. Use :func:`~fastf1.plotting.get_team_name` instead.
"""

_DEPR_COLOR_PALETTE: List[str] = _COLOR_PALETTE.copy()
COLOR_PALETTE: Dict[str, str]
"""
The default color palette for matplotlib plot lines in fastf1's color scheme.
.. deprecated:: 3.3.0
The ``COLOR_PALETTE`` list is deprecated and will be removed in a
future version with no replacement.
"""


def get_compound_color(compound: str, *, session: Session) -> str:
"""
Get the compound color as hexadecimal RGB color code for a given compound.
Args:
compound: The name of the compound
session: the session for which the data should be obtained
Returns: A hexadecimal RGB color code
"""
year = str(session.event['EventDate'].year)
return _Constants[year].CompoundColors[_Compounds(compound.upper())]
33 changes: 33 additions & 0 deletions fastf1/plotting/_constants/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import (
Dict,
Type
)

from fastf1.plotting._constants.base import (
BaseSeason,
Colormaps
)
from fastf1.plotting._constants.season2023 import Season2023
from fastf1.plotting._constants.season2024 import Season2024


# Deprecated, will be removed for 2025
LEGACY_TEAM_TRANSLATE: Dict[str, str] = {
'MER': 'mercedes',
'FER': 'ferrari',
'RBR': 'red bull',
'MCL': 'mclaren',
'APN': 'alpine',
'AMR': 'aston martin',
'SAU': 'sauber',
'VIS': 'visa', # TODO: update
'HAA': 'haas',
'WIL': 'williams'
}


Constants: Dict[str, Type[BaseSeason]] = {
'2023': Season2023,
'2024': Season2024
}

Loading

0 comments on commit a1ed97c

Please sign in to comment.