Charlie Vagg
Charlie Vagg

Reputation: 97

How to highlight the lowest line on a linegraph in matplotlib?

Currently, my code generates a line graph based on an array of x,y values generated from a function called f(), like so:

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

This generates a graph like so:

enter image description here

Is there a streamlined way to make all of the lines a grey, highlighting the line with the lowest endpoint with red and highest endpoint with green, on the x-axis, regardless of what y is?

So for this example, where T=5 the line would be red and where T=3 the line would be green, and for the other lines all the same shade of grey.

Upvotes: 0

Views: 315

Answers (1)

RandomGuy
RandomGuy

Reputation: 1207

Simply store all your x and y values in two lists :

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

Then find the highest and lowest value :

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()

Upvotes: 1

Related Questions