some_programmer
some_programmer

Reputation: 3528

How to plot vertical lines on an already plotted line plot?

I am trying to plot vertical lines in a line lot that I have already plotted.

Just a small portion of my data looks as follows:

EscAct_Curr_A   StepID  Time_Elapsed
0.122100122272968   1   0.0
0.0                 2   0.101
0.0                 2   0.432
0.122100122272968   2   1.422
0.122100122272968   2   2.422
0.122100122272968   2   3.422
0.122100122272968   2   4.432
0.122100122272968   2   5.938
0.122100122272968   2   6.49
0.122100122272968   5   7.928
0.122100122272968   5   8.938
0.122100122272968   5   9.938

While plotting the entire data on the graph, I use the following code:

x = data['Time_Elapsed']
y = data['EscAct_Curr_A']
plt.plot(x, y)
plt.show()

and I get the following graph:

enter image description here

What I want to do now is to find the minimum time of each StepID and plot a vertical line on the graph above.

For example:

From the above data we can see that 0.0 is the minimum time for StepID 1, so a vertical line must be drawn at 0.0 and must be named as 1, then for StepID 2, 0.101 is the minimum time, so a vertical line at 0.101 must be drawn and must be named as 2 and so on.

I would like to know how can this be done either in matplotlib or in seaborn

Thanks

Upvotes: 0

Views: 398

Answers (3)

freerafiki
freerafiki

Reputation: 561

I guess the problem is also finding the minimums, the vertical line is already answered here

import numpy as np

# build an array with the stepIDs
stepIDs = np.unique(data['stepID'])
minTimes = np.zeros_like(stepIDs)

# then loop through it
for j in range(len(stepIDs)):
  currentID = stepIDs[j]
  currentTimes = data['Time_Elapsed'][np.where(data['stepID'] == currentID)]
  minTimes[j] = min(currentTimes)

# then just plot the lines as explained in 
# https://stackoverflow.com/questions/24988448/how-to-draw-vertical-lines-on-a-given-plot-in-matplotlib
for minTime in minTimes:
    plt.axvline(x=minTimes) 

Upvotes: 0

Mike O'Connor
Mike O'Connor

Reputation: 2700

Compute your mintimes, say as a list. Then, before plt.show put in a for loop for all of your mintimes and stepids (there should be one stepid for each mintime):

for i in range(len(mintimes)):
    plt.axvline(x=mintime[i], color='b')
    plt.figtext( mintime[i], y_convenient, str(stepid[i]), color='tab:brown', size='x-small', fontweight='bold' )

So y_convenient would be some height that you prefer to show the stepids at. I have indicated some formatting possibilities. You will want to tweak things, such as maybe adding an offset to mintime[i] for readability.

Upvotes: 0

Tojra
Tojra

Reputation: 683

A simple approach:

m=0
tm=data['Time_Elapsed']
for i,val in enumerate(data['StepID']):
    if(val!=m):#detect change in val
       m=val
       plt.plot([tm[i],tm[i]],[0,1])#plot a vertical line

Upvotes: 1

Related Questions