Gabriel
Gabriel

Reputation: 3797

matplotlib conditional background color in python

How can I change the background color of a line chart based on a variable that is not in the chart? For example if I have the following dataframe:

import numpy as np
import pandas as pd

dates = pd.date_range('20000101', periods=800)
df = pd.DataFrame(index=dates)
df['A'] = np.cumsum(np.random.randn(800))  
df['B'] = np.random.randint(-1,2,size=800)

If I do a line chart of df.A, how can I change the background color based on the values of column 'B' at that point in time?

For example, if B = 1 in that date, then background at that date is green.

If B = 0 then background that date should be yellow.

If B = -1 then background that date should be red.

Adding the workaround that I originally was thinking of doing with axvline, but @jakevdp answer is what exactly was looking because no need of for loops: First need to add an 'i' column as counter, and then the whole code looks like:

dates = pd.date_range('20000101', periods=800)
df = pd.DataFrame(index=dates)
df['A'] = np.cumsum(np.random.randn(800))  
df['B'] = np.random.randint(-1,2,size=800)
df['i'] = range(1,801)

# getting the row where those values are true wit the 'i' value
zeros = df[df['B']== 0]['i'] 
pos_1 = df[df['B']==1]['i']
neg_1 = df[df['B']==-1]['i']

ax = df.A.plot()

for x in zeros:
    ax.axvline(df.index[x], color='y',linewidth=5,alpha=0.03)
for x in pos_1:
     ax.axvline(df.index[x], color='g',linewidth=5,alpha=0.03)
for x in neg_1:
     ax.axvline(df.index[x], color='r',linewidth=5,alpha=0.03)

enter image description here

Upvotes: 6

Views: 17469

Answers (1)

jakevdp
jakevdp

Reputation: 86320

You can do this with a plot command followed by pcolor() or pcolorfast(). For example, using the data you define above:

ax = df['A'].plot()
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
              df['B'].values[np.newaxis],
              cmap='RdYlGn', alpha=0.3)

enter image description here

Upvotes: 15

Related Questions