我正在做一個個人項目,我想畫出每個一級方程式車手在排位賽中的最佳時間(分三個部分:第一季度、第二季度和第三季度)
繪圖將在y-axis上顯示驅動程序的名稱(按其最終結果排序:第一個在頂部,最后一個在底部),在x-axis上的時間如下所示,4個驅動程序的Excel表示:
通過Python,我能夠收集每個會話(Q1、Q2和Q3)的最佳時間,我將其存儲為列表(t_Q1,t_Q2,t_Q3)中的列表,以及它們的最終位置。以下是代碼的開頭:
import matplotlib.pyplot as plt
import numpy as np
Drivers_name=['VER','HAM','VET','MSC'] #for the label of the Y-axis
Drivers_position=[1,2,12,20]
Drivers_timings=[[94.352,93.464,92.91],[94.579,93.797,93.119],[95.281,95.5],[96.119]]
fig,ax = plt.subplots()
y=np.arange(len(Drivers_name))
for i in range(len(Drivers_name)):
if len(Drivers_timings[i])==3:
eps=0.2
ax.barh(y-eps,Drivers_timings[i][0],height=eps,color='g', label='Q1')
ax.barh(y,Drivers_timings[i][1],height=eps,color='r', label='Q2')
ax.barh(y+eps,Drivers_timings[i][1],height=eps,color='b', label='Q3')
elif len(Drivers_timings[i])==2:
eps=0.2
ax.barh(y-eps/2,Drivers_timings[i][0],height=eps,color='g', label='Q1')
ax.barh(y+eps/2,Drivers_timings[i][1],height=eps,color='r', label='Q2')
elif len(Drivers_timings[i])==1:
ax.barh(y,Drivers_timings[i][0],height=0.2,color='g', label='Q1')
plt.yticks(y,Drivers_name)
plt.legend()
plt.show()
但這是我執行它時得到的:
我們可以注意到,它并沒有真正代表我所尋找的,并且圖例多次顯示相同的元素(這是正常的,因為label
參數在for
循環中,但我無法理解任何其他想法)
評論:總結一下,以下是我的帖子的目的
- 獲得預期圖(我用Excel獲得的圖)
- 固定圖例框
通過使用
ax.barh(y-eps, ...)
,其中y=np.arange(len(Drivers_name))
,在每個步驟中,為所有y-values創建循環條。例如,對于i=0
,將在y=0
周圍創建三個條形圖,但也會在y=1
周圍創建三個條形圖,在y=2
周圍創建三個條形圖,在y=3
周圍創建三個條形圖。用i
替換y
會產生所需的效果。每次使用
label=
時,圖例都包含一行。在完整的繪圖中,ax.barh
將被調用9次,每次調用label=
。解決方案是從虛擬矩形創建圖例。