Skip to content

Commit

Permalink
ENH: reimplement plotting module
Browse files Browse the repository at this point in the history
  • Loading branch information
theOehrly committed May 11, 2024
1 parent 869d31f commit cabccc9
Show file tree
Hide file tree
Showing 45 changed files with 2,828 additions and 313 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fastf1/tests/mpl-baseline-new/

# documentation build directories
docs/_build/
docs/examples_gallery/
docs/gen_modules/
**/sg_execution_times.rst

# all variations of cache directories
Expand Down
77 changes: 77 additions & 0 deletions docs/_plots/colormap_overview.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import matplotlib.pyplot as plt

from fastf1.plotting._constants import Constants


n = len(Constants) # total number of years

# dynamically adjust figure size depending on number of required subplots
fig = plt.figure(figsize=(10, 3 * n))

# slightly paranoid, sort years explicitly (order is not necessarily
# guaranteed in the internal code)
years_sorted = [str(year) for year in
sorted((int(year) for year in Constants.keys()), reverse=True)]

# generate one axis/graphic for each year
for i, year in enumerate(years_sorted):
teams = Constants[year].Teams

ax = fig.add_subplot(n, 1, i + 1)

x_labels = list()
x_ranges = list()
default_colors = list()
official_colors = list()

for j, (name, team) in enumerate(teams.items()):
x_labels.append(team.ShortName)
default_colors.append(team.TeamColor.Default)
official_colors.append(team.TeamColor.Official)

x_ranges.append((j + 0.5, 1))

# draw color rectangles as horizontal bar graph
ax.broken_barh(x_ranges, (0.5, 0.9), facecolors=official_colors)
ax.broken_barh(x_ranges, (1.5, 0.9), facecolors=default_colors)

# configure y axis and label
ax.set_ylim((0.5, 2.5))
ax.set_yticks([1, 2])
ax.set_yticklabels(['official', 'default'])

# configure x axis and label
ax.set_xlim((0.5, len(x_ranges) + 0.5))
ax.set_xticks(range(1, len(x_labels) + 1))
ax.set_xticklabels(x_labels)

# disable frame around axis
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

# disable tick markers everywhere, label x axis at the top
ax.tick_params(top=False, labeltop=True, bottom=False, labelbottom=False,
left=False, labelleft=True, right=False, labelright=False)

# set tick label text color (grey, so it works on light and dark theme and
# isn't too distracting next to the colors)
ax.tick_params(colors='#787878')

# set background color within axes
# (transparent, fallback white if transparency not supported)
ax.set_facecolor('#ffffff00')

# set axes title (grey, so it works on light and dark theme and
# isn't too distracting next to the colors)
ax.set_title(year, color='#787878')

# set background color for figure/margins around axes
# (transparent, fallback white if transparency not supported)
fig.patch.set_facecolor('#ffffff00')

# adjust margins between and around axes
plt.subplots_adjust(top=0.95, bottom=0.05, left=0.1, right=0.95, hspace=0.5)

plt.show()
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.3.x.rst
.. include:: v3.4.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.3.x
v3.2.x
v3.1.x
v3.0.x
Expand Down
37 changes: 37 additions & 0 deletions docs/changelog/v3.4.x.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

What's new in v3.4.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
13 changes: 12 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
warnings.filterwarnings(action='ignore',
message=r'`utils.delta_time` is considered '
r'deprecated.*')
warnings.filterwarnings(action='ignore',
message=r'(COMPOUND_COLORS|DRIVER_COLORS|'
r'DRIVER_TRANSLATE|TEAM_COLORS|TEAM_TRANSLATE|'
r'COLOR_PALETTE) is deprecated and.*')

doc_cache = os.path.abspath('../doc_cache')

Expand Down Expand Up @@ -84,6 +88,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 Expand Up @@ -151,13 +156,19 @@ def sphinx_gallery_setup(gallery_conf, fname):

sphinx_gallery_conf = {
'examples_dirs': '../examples',
'gallery_dirs': 'examples_gallery',
'gallery_dirs': 'gen_modules/examples_gallery',
'download_all_examples': False,
'remove_config_comments': True,
'image_scrapers': ('matplotlib', # default
plotly_sg_scraper), # for plotly thumbnail
'reset_modules': ('matplotlib', 'seaborn', # defaults
sphinx_gallery_setup), # custom setup
# directory where function/class granular galleries are stored
'backreferences_dir': 'gen_modules/backreferences',

# Modules for which function/class level galleries are created. In
# this case sphinx_gallery and numpy in a tuple of strings.
'doc_module': ('fastf1', ),
'expected_failing_examples': ('../examples/plot_qualifying_results.py', ),
}

Expand Down
2 changes: 1 addition & 1 deletion docs/examples/basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -336,5 +336,5 @@ So let's see what the fastest lap time was and who is on pole.


Check out this example that shows how you can plot lap times:
:ref:`sphx_glr_examples_gallery_plot_qualifying_results.py`
:ref:`sphx_glr_gen_modules_examples_gallery_plot_qualifying_results.py`

2 changes: 1 addition & 1 deletion docs/examples/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ For some more advanced stuff, it's just a few more steps.
import fastf1
import fastf1.plotting

fastf1.plotting.setup_mpl()
fastf1.plotting.setup_mpl(misc_mpl_mods=False, color_scheme='fastf1')

session = fastf1.get_session(2019, 'Monza', 'Q')

Expand Down
4 changes: 2 additions & 2 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ tyre data, weather data, the event schedule and session results.


To get a quick overview over how to use FastF1, check out
:doc:`examples/index` or the :doc:`examples_gallery/index`.
:doc:`examples/index` or the :doc:`gen_modules/examples_gallery/index`.

Note that FastF1 handles big chunks of data (~50-100mb per session). To improve
performance, data is per default cached locally. The default placement
Expand Down Expand Up @@ -141,7 +141,7 @@ Contents
:caption: Contents:

examples/index
examples_gallery/index
gen_modules/examples_gallery/index
fastf1
core
events
Expand Down
126 changes: 125 additions & 1 deletion docs/plotting.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,130 @@
Plotting - :mod:`fastf1.plotting`
=================================

Helper functions for creating data plots.

:mod:`fastf1.plotting` provides optional functionality with the intention of
making it easy to create nice plots.

This module mainly offers:
- team names and colors
- driver names and driver abbreviations
- Matplotlib integration and helper functions

FastF1 focuses on plotting with Matplotlib or related libraries like Seaborn.
If you wish to use these libraries, it is highly recommended to enable
extend support for these by calling :func:`~fastf1.plotting.setup_mpl`.


Team Colormaps
--------------

Currently, two team colormaps are supported. Each colormap provides one color
for each team. Colors are constant over the course of a season. All functions
that return colors for teams or drivers accept an optional ``colormap``
argument.

The ``'default'`` colormap is FastF1's default colormap. These colors are teams'
primary colors or accent colors as they are used by the teams on their website
or in promotional material. The colors are chosen to maximize readability in
plots by creating a stronger contrast while still being associated with the
team.

The ``'official'`` colormap contains the colors exactly as they are used by
the FOM in official graphics and in the TV graphics. Those colors are often
slightly muted. While that makes them more pleasing to look at in some graphics,
it also reduces the contrast between colors which is often bad for
readability of plots.

See here for a complete list of all colors: :ref:`Team-Colormaps-Overview`


.. note:: **Driver Colors**

Previously, individual colors for each driver were provided. This is no
longer the case. The driver color is now equivalent to the team color,
meaning that drivers from the same team have the exact same color. This
change was made because different colors for 20 drivers end up looking
very similar in many cases anyway, meaning it is not a good solution to
use these to distinguish different drivers. Other means of plot styling
should be used instead.



Overview
--------


Configuration and Setup
^^^^^^^^^^^^^^^^^^^^^^^

.. automodule:: fastf1.plotting
:noindex:
:no-members:
:autosummary:
:autosummary-members:
setup_mpl


Get Colors, Names and Abbreviations for Drivers or Teams
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. automodule:: fastf1.plotting
:noindex:
:no-members:
:autosummary:
:autosummary-members:
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


List all Names and Abbreviations for Drivers/Teams in a Session
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. automodule:: fastf1.plotting
:noindex:
:no-members:
:autosummary:
:autosummary-members:
get_compound_mapping,
get_driver_color_mapping,
list_driver_abbreviations,
list_driver_names,
list_short_team_names,
list_team_names


Plot Styling
^^^^^^^^^^^^

.. automodule:: fastf1.plotting
:noindex:
:no-members:
:autosummary:
:autosummary-members:
add_sorted_driver_legend


Deprecated Functionality
^^^^^^^^^^^^^^^^^^^^^^^^

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





Plotting API Reference
----------------------

.. automodule:: fastf1.plotting
:members:
:show-inheritance:
11 changes: 11 additions & 0 deletions docs/plotting_colormaps.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

:orphan:

.. _Team-Colormaps-Overview:

Overview over Team Colormaps
----------------------------


.. plot:: _plots/colormap_overview.py
:include-source: False
10 changes: 6 additions & 4 deletions examples/plot_annotate_speed_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
import fastf1.plotting


# enable some matplotlib patches for plotting timedelta values and load
# FastF1's default color scheme
fastf1.plotting.setup_mpl(misc_mpl_mods=False)
# Enable Matplotlib patches for plotting timedelta values and load
# FastF1's dark color scheme
fastf1.plotting.setup_mpl(mpl_timedelta_support=True, misc_mpl_mods=False,
color_scheme='fastf1')

# load a session and its telemetry data
session = fastf1.get_session(2021, 'Spanish Grand Prix', 'Q')
Expand All @@ -35,7 +36,8 @@
# Finally, we create a plot and plot the speed trace as well as the corner
# markers.

team_color = fastf1.plotting.team_color(fastest_lap['Team'])
team_color = fastf1.plotting.get_team_color(fastest_lap['Team'],
session=session)

fig, ax = plt.subplots()
ax.plot(car_data['Distance'], car_data['Speed'],
Expand Down
Loading

0 comments on commit cabccc9

Please sign in to comment.