4

I am comparing and plotting two arrays and I'd like to plot them and also highlight in some color the areas where array a is less than array b. This is the code that I am trying to work with, where c is places where a is less than b:

import pandas
import numpy

numpy.random.seed(10)

df = pandas.DataFrame(numpy.random.randn(10, 2), columns=['a', 'b'])

df['c'] = df['a'] < df['b']

and the resultant DataFrame is:

          a         b      c
0  1.331587  0.715279  False
1 -1.545400 -0.008384   True
2  0.621336 -0.720086  False
3  0.265512  0.108549  False
4  0.004291 -0.174600  False
5  0.433026  1.203037   True
6 -0.965066  1.028274   True
7  0.228630  0.445138   True
8 -1.136602  0.135137   True
9  1.484537 -1.079805  False

Here is the beautiful example I made in ol' trusty MS Paint (RIP) that shows what I'd like to make:

enter image description here

user1367204
  • 4,549
  • 10
  • 49
  • 78

1 Answers1

9

You can try something like this by using axvspan. You can avoid creating the dedicated c column.

ax = df.plot()

def highlight(indices,ax):
    i=0
    while i<len(indices):
        ax.axvspan(indices[i]-0.5, indices[i]+0.5, facecolor='pink', edgecolor='none', alpha=.2)
        i+=1

highlight(df[df['a'] < df['b']].index, ax)

enter image description here

Romain
  • 19,910
  • 6
  • 56
  • 65
  • 1
    Thank you! For those using datetime indices, I did M15 = dt.timedelta(minutes=15) then ax.axvspan(indices[i] - M15, indices[i] + M15, ...) – Flint O'Brien Mar 17 '18 at 22:15
  • 1
    Unlike the other post of which this is marked duplicate, this shows how to get multiple spans. – abhishah901 May 19 '20 at 23:26