6

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

2
  • The background color of what? The chart? The text label? The color of the datapoint itself? Please show an example. Commented Oct 26, 2015 at 22:16
  • The background color of the chart. Was thinking of doing it with vertical lines, but not sure if its the most efficient way. Commented Oct 26, 2015 at 22:20

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

4 Comments

Probably want to use a negative z-order as well.
I'd like to add that this does NOT work correctly, when you plot different dfs (with different time axes) into one axis.
Which I can't really reproduce in a minimal working example right now... but the point stands that it plots nonsense when I plot two time series with different lengths and frequencies on one axis.
How do you specify the mapping between value and color using pcolorfast? For example, re-using the OP's original question, how would I map 0 to yellow, 1 to green, and -1 to red?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.