2
import pandas as pd
import matplotlib.pyplot as plt
trend=[0,0,0,1,1,1,-1,-1,-1,1,1,1,0,0,0,1,1,1,-1,-1]
price= [1,2,3,4,5,6,5,4,3,4,5,6,7,8,9,8,7,6,5,4]
df1= pd.DataFrame({'Trend':trend,'Price':price})

def plot_func(group):
    global ax
    if (group.Trend ==-1).all() :
        color = 'r'
    elif (group.Trend ==1).all() :
        color ='g'
    elif (group.Trend == 0).all() :
        color='b'
    lw = 2.0
    ax.plot(group.index, group.Price, c=color, linewidth=lw) 

fig, ax = plt.subplots()
df1.groupby((df1.Trend.shift() != df1.Trend).cumsum()).apply(plot_func)

Hi guys,

Need some advice on my code. I tried to plot the price data using matplotlib with multicoloured lined based on the trend condition but somehow the lines are disconnected and I have no idea how to make them continuous. Pls help.

Thks a lot, John

My plot

1
  • See this tutorial where your Trend column plays the role of dydx. Commented Apr 29, 2021 at 14:48

1 Answer 1

2

This is because the groups are separated and your code only plots within each group. Try (similar to the link in the comment):

for trend, prev, cur in zip(df1.Trend.iloc[1:], df1.index[:-1], df1.index[1:]):
    if trend==-1: 
        color='r'
    elif trend==1:
        color='g'
    else:
        color='b'
    
    plt.plot([prev,cur],df1.loc[[prev,cur],'Price'], c=color)

Output:

enter image description here

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

1 Comment

Thks for your help!

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.