pandas - Plot Multicolored line based on conditional in python -


i have pandas dataframe 3 columns , datetime index

date        px_last  200dma     50dma            2014-12-24  2081.88 1953.16760  2019.2726 2014-12-26  2088.77 1954.37975  2023.7982 2014-12-29  2090.57 1955.62695  2028.3544 2014-12-30  2080.35 1956.73455  2032.2262 2014-12-31  2058.90 1957.66780  2035.3240 

i make time series plot of 'px_last' column colored green if on given day 50dma above 200dma value , colored red if 50dma value below 200dma value. have seen example, can't seem make work case http://matplotlib.org/examples/pylab_examples/multicolored_line.html

here example without matplotlib.collections.linecollection. idea first identify cross-over point , using plot function via groupby.

import pandas pd import numpy np import matplotlib.pyplot plt  # simulate data # ============================= np.random.seed(1234) df = pd.dataframe({'px_last': 100 + np.random.randn(1000).cumsum()}, index=pd.date_range('2010-01-01', periods=1000, freq='b')) df['50dma'] = pd.rolling_mean(df['px_last'], window=50) df['200dma'] = pd.rolling_mean(df['px_last'], window=200) df['label'] = np.where(df['50dma'] > df['200dma'], 1, -1)   # plot # ============================= df = df.dropna(axis=0, how='any')  fig, ax = plt.subplots()  def plot_func(group):     global ax     color = 'r' if (group['label'] < 0).all() else 'g'     lw = 2.0     ax.plot(group.index, group.px_last, c=color, linewidth=lw)  df.groupby((df['label'].shift() * df['label'] < 0).cumsum()).apply(plot_func)  # add ma lines ax.plot(df.index, df['50dma'], 'k--', label='ma-50') ax.plot(df.index, df['200dma'], 'b--', label='ma-200') ax.legend(loc='best') 

enter image description here


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -