title: matplotlib conditional background color in python
body: <p>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:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>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? </p>
  
  <p>For example, if B = 1 in that date, then background at that date is green. </p>
  
  <p>If B = 0 then background that date should be yellow.</p>
  
  <p>If B = -1 then background that date should be red. </p>
  
  <p>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:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/dSu9K.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/dSu9K.jpg" alt="enter image description here"></a></p>