So basically I'm trying to plot the lap time of 2 F1 drivers and I'd like to show when the Safety Car is out. By the way, I can't show in the same time a legend where I can see, the drivers' name and the Safety Car deployed all at once. I have the same issue to change to marker on the lap where the driver is pitting to change tires.
Here are the lists which are used in the code :
lap=[1, 2, 3, 4, 5, 6, 7, 8, 9]
info=['SC', 'SC', 'SC', None, None, None, None, None, None]
time_lec=[145.323, 141.062, 142.84, 145.489, 136.873, 99.585, 94.848, 92.511, 91.679]
time_nor=[142.471, 139.843, 147.079, 141.984, 130.516, 104.428, 98.389, 94.898, 93.029]
info_lec=[None, None, None, None, None, 'P', None, None, None]
info_nor=[None, None, None, None, 'P', None, None, None, None]
Here is the code to display the drivers legend:
import matplotlib.pyplot as plt
for i in range(0,len(info)):
if info[i]=='SC':
plt.axvspan(i+1,i+2,facecolor='yellow',alpha=0.5) #Display when Safety Car is deployed
if info_lec[i]=='P': #Remove time lost during pitstop
time_lec[i]=time_lec[i]-25
if info_nor[i]=='P':
time_nor[i]=time_nor[i]-25
plt.plot(lap,time_lec,'.:r',label='Leclerc',linewidth=1.2)
plt.plot(lap,time_nor,'.:b',label='Norris',linewidth=1.2)
for i in range(0,len(info)): #Displaying the lap where the driver is pitting (to change tires)
if info_lec[i]=='P':
plt.plot(lap[i],time_lec[i],'xr')
if info_nor[i]=='P':
plt.plot(lap[i],time_nor[i],'xb')
plt.legend()
plt.xlabel('Lap')
plt.ylabel('Time (sec)')
plt.show()
And here is the code to display the safety car legend:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
for i in range(0,len(info)):
if info[i]=='SC':
plt.axvspan(i+1,i+2,facecolor='yellow',alpha=0.5) #Display when Safety Car is deployed
if info_lec[i]=='P': #Remove time lost during pitstop
time_lec[i]=time_lec[i]-25
if info_nor[i]=='P':
time_nor[i]=time_nor[i]-25
plt.plot(lap,time_lec,'.:r',label='Leclerc',linewidth=1.2)
plt.plot(lap,time_nor,'.:b',label='Norris',linewidth=1.2)
for i in range(0,len(info)): #Displaying the lap where the driver is pitting (to change tires)
if info_lec[i]=='P':
plt.plot(lap[i],time_lec[i],'xr')
if info_nor[i]=='P':
plt.plot(lap[i],time_nor[i],'xb')
sc_patch = mpatches.Patch(color='yellow', alpha=0.5, label='Safety car')
plt.legend(handles=[sc_patch])
plt.xlabel('Lap')
plt.ylabel('Time (sec)')
plt.show()
Note: If I'm adding plt.legend()
just before plt.show()
, we will not see the safety car legend
And here are the two legends I can get even though I would like to have everything at once : We can notice the the marker changed for the pit stop (lap 28) but is not shown in any legend boxes
The objective is to have the 2 legends as one : One legend where there are Leclerc, Norris, Safety Car, Red Flag