How to highlight areas in pandas plot?

I compare and draw two arrays, and I would like to build them, as well as highlight in some color areas where the array is asmaller than the array b. This is the code I'm trying to work with, where care the places where aless is 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 resulting DataFrame:

          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 a great example that I did in gullible MS Paint (RIP) that shows what I would like to do:

enter image description here

+4
source share
1 answer

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

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)

+4
source

Source: https://habr.com/ru/post/1693755/


All Articles