Home > Blockchain >  Struggling to displaying the right (formatted) value for a matplotlib labels
Struggling to displaying the right (formatted) value for a matplotlib labels

Time:09-07

Guide: enter image description here

(Is this TimeDelta[ns] in an integer under scientific notation? The dtype is timedelta64[ns])

Expected Values: The amount of time each driver is from the leader (s.ms) (HAM=0.038). Note: order is the same

enter image description here

print(times)

Code:

#!/usr/bin/python3-64

#required packages
#pip3 install fastf1
#pip3 install pandas
#pip3 install matplotlib
#pip3 install numpy

import matplotlib.pyplot as plt
import matplotlib.patches as pat
import fastf1 as ff1
import fastf1.plotting as ff1p
ff1p.setup_mpl(mpl_timedelta_support=True, color_scheme=None, misc_mpl_mods=False)
from fastf1.core import Laps
import pandas as pd
import numpy as np
from timple.timedelta import strftimedelta as td
import os
l=str.lower

def data_cache():
    cache='/ff1_temp' #temp cache
    while(True):
        warn=input(l(f'!WARNING! A data cache will be made at {cache}\n'
                     f'Formula 1 Race Data will be downloaded to {cache}\n'
                     f'Would you like to continue? [y/n]\n'))
        if(warn=='n'):
            print('Quitting!\n')
            exit(0)
        elif(warn=='y'):
            print(f'cache location: {cache}\n')
            if not os.path.exists(cache): # os.path.exists(cache)
                os.mkdir(cache) # os.mkdir(cache)
            ff1.Cache.enable_cache(cache) # Fast F1 Cache API
            break
        else:
            print('Plese Enter [y/n]\n')
            continue
    
def data_load():
    data=ff1.get_session(2021,'Netherlands','Q') #Y,L,S = Year, Location, Session
    data.load(laps=True,telemetry=False,weather=False,messages=False)
    return(data)

def data_graph():
    data=data_load()
    drivers=pd.unique(data.laps['DriverNumber'])
    fll=list()
    for row in drivers: #get fastest laps for session from each driver
       fld=data.laps.pick_driver(row).pick_fastest()
       fll.append(fld)
    fl=Laps(fll).sort_values(by='LapTime').reset_index(drop=True)
    flf=fl.pick_fastest() 
    fl['LapTimeDelta']=fl['LapTime']-flf['LapTime'] #determine the TimeDelta from leader
    tc=list()
    for index, lap in fl.iterlaps(): #team colours
        color=ff1p.team_color(lap['Team'])
        tc.append(color)
    return(fl,tc,flf)

def data_plot():
    fl,tc,flf=data_graph()
    fig,ax=plt.subplots()
    times=fl['LapTimeDelta']
    fli=fl.index
    #             y    x
    bars=ax.barh(fli,times, color=tc,edgecolor='grey')

    print(times) #expected values

    ax.set_yticks(fl.index)
    ax.set_yticklabels(fl['Driver'])
    ax.set_xlabel('Time Difference (ms)')

    #should be x axis?
    ax.bar_label(bars) #(times)

    ax.invert_yaxis()
    lt=td(flf['LapTime'], '%m:%s.%ms')
    plt.suptitle(f'2021 Dutch GP Qualifying\n'
        f"Fastest  at {lt} ({flf['Driver']})")
    plt.show()

if(__name__=="__main__"):
    data_cache()
    data_plot()
    exit(0)

results of print(bars)

print(bars)

results of print(type(times)) and print(type(bars))

print(type(times)) && print(type(bars))

What has been Attempted:

def data_plot():
    ax.bar_label(times)

Traceback (most recent call last):
  File "\python\datacollection\fp1.ff1.graph.py", line 144, in <module>
    data_plot()
  File "\python\datacollection\fp1.ff1.graph.py", line 132, in data_plot
    ax.bar_label(times)
  File "\Python\Python310\lib\site-packages\matplotlib\axes\_axes.py", line 2609, in bar_label
    bars = container.patches
  File "\Python\Python310\lib\site-packages\pandas\core\generic.py", line 5575, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'Lap' object has no attribute 'patches'

---

def data_plot_label(fli,times):
    for i in range(len(fli)):
        plt.text(i,times[i],times[i],ha='center',bbox=dict(alpha=0.8))

def data_plot():
    data_plot_label(fli,times)

failed attempt

Close:

I'm still pretty green with this stuff,

  1. Am I going about this correctly?
  2. What are my options regarding labelling and matplotlib?
  3. How do I set the correct formatted value for this label?

I find the graph is harder to understand without the actual values on it. It has less depth.

Relevant Docs:

  • enter image description here

    Just a little more formatting and it should look great!

  • Related