如何在matplotlib中突出显示折线图上的最低线?

时间:2020-08-23 16:17:00

标签: python matplotlib

目前,我的代码基于从称为f()的函数生成的x,y值数组生成线形图,如下所示:

T = 0
for i in range(0,10):
    
    #function f generates array of values based on T to plot x,y
    x,y = f(T)

    plt.plot(x, y, label = "T={}".format(T))
    
    T += 1

这将生成如下图:

enter image description here

是否有一种简化的方法使所有线条变为灰色,无论y是多少,都在x轴上突出显示了最低端点为红色的端点,最高端点为绿色的端点?

因此,在此示例中,在T = 5的情况下,该行为红色,在T = 3的情况下,该行为绿色,而对于其他行,它们都使用相同的灰色阴影。

1 个答案:

答案 0 :(得分:1)

只需将您的所有xy值存储在两个列表中:

X = [x0,..., x9] # List of lists.
Y = [y0,..., y9] # Same. x0, y0 = f(0)

然后找到最高和最低值:

highest_endpoint, highest_endpoint_indice = Y[0][-1], 0 # Initialisation.
lowest_endpoint, lowest_endpoint_indice = Y[0][-1], 0 # Initialisation.

for i, y in enumerate(Y[1:]) : # No need to check for Y[0] = y0 thanks to the initialisations.
  if y[-1] > highest_endpoint : # If current endpoint is superior to temporary highest endpoint.
    highest_endpoint, highest_endpoint_indice = y[-1], i+1
  elif y[-1] < lowest_endpoint :
    lowest_endpoint, lowest_endpoint_indice = y[-1], i+1

# Plot the curves.
for T in range(10) :
  if T == highest_endpoint_indice :
    plt.plot(X[T], Y[T], label = "T={}".format(T), color = 'green')
  elif T == lowest_endpoint_indice :
    plt.plot(X[T], Y[T], label = "T={}".format(T), color = 'red')
  else :
    plt.plot(X[T], Y[T], label = "T={}".format(T), color = 'gray')

plt.show()