0

Basically I have a panda dataframe looking like this:

                time    price   trend   related_price
1   2019-10-23 15:00:01 6748.9  no trend    
2   2019-10-23 15:00:02 6749.1  increasing  6749.1  
3   2019-10-23 15:00:03 6749.0  no trend    
4   2019-10-23 15:00:04 6749.0  no trend    
5   2019-10-23 15:00:05 6748.0  decreasing  6748
6   2019-10-23 15:00:06 6749.0  no trend    

What I would like is to plot the column price over time, and when the column trend becomes increasing then the line price becomes green and when the column trend becomes decreasing then the line price becomes red. I went through the documentation, but did not find any way to do so, any clue? thanks!

1 Answer 1

1

I am not sure if this is the most elegant way since I am fairly new to Python, but this seems to accomplish what you are looking for.

First, import relevant libraries:

import pandas as pd
import matplotlib.pyplot as plt

Then, plot all the price data as a black line:

plt.plot(df['time'], df['price'], c = 'k')

Finally, loop over the combinations of consecutive rows of the price column (because this is really what you want to be color coded, not the points themselves). The code here will identify if the second element in each combination of consecutive elements was akin to an increase or decrease. If it was an increase, it will plot a green line over that segment of the black line. Conversely, if it was a decrease, it will plot a red line over that segment of the black line.

for val in range(2, len(df)+1):   
    start = val - 2
    focal_val = val -1
    if df['trend'][focal_val] == 'increasing':
        plt.plot(df['time'][start:val], df['price'][start:val], c = 'g')
    elif df['trend'][focal_val] == 'decreasing':
        plt.plot(df['time'][start:val], df['price'][start:val], c = 'r')

The final graph looks like this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.