Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 827
Gabriel Avatar asked Oct 26 '15 21:10

Gabriel


People also ask

How do I change the background color in Matplotlib?

Matplotlib change background color inner and outer color set_facecolor() method is used to change the inner background color of the plot. figure(facecolor='color') method is used to change the outer background color of the plot. In the above example, we have change both an inner and outer color of background of plot.

How do I change the background color in python?

Right-click the upper-left corner of the Python console window and select Properties. In the dialog box that appears, pick the tab labeled Colors. On it you can set the screen background and text color.


1 Answers

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

like image 89
jakevdp Avatar answered Oct 07 '22 03:10

jakevdp