Reputation: 360
I have df1 and df2. I want to show bars in cells of df1 using values from df2. I was able to apply other forms of styling using below code, but with bars you cannot use this method.
def color_cells(s):
if s > 90:
return 'color:{0}; font-weight:bold'.format('green')
elif s>80:
return 'background-color: light yellow;color:{0}; font-weight:regular'.format('dark yellow')
else:
return 'color:{0}; font-weight:bold'.format('red')
df1.style.apply(lambda x: df2.applymap(color_cells), axis=None)
My code for getting bars in df2 is
df2.style.bar(color=['#d65f5f', '#5fba7d'])
How do I apply above code to df1? Index and column names are same.
Adding sample dataframe:
df1=pd.DataFrame(np.random.rand(15, 10))
df2=pd.DataFrame(np.random.rand(15, 10)*100)
Upvotes: 1
Views: 967
Reputation: 12503
Here's the code that does that:
df1=pd.DataFrame(np.random.rand(15, 10))
df2=pd.DataFrame(np.random.rand(15, 10)*100)
pct = (df2 - df2.min()) / (df2.max() - df2.min() )*100
def make_bar_style(x):
return f"background: linear-gradient(90deg,#5fba7d {x}%, transparent {x}%); width: 10em"
pct.applymap(make_bar_style).shape
df1.style.apply(lambda x: pct.applymap(make_bar_style), axis=None)
The result is:
To demonstrate the fact that bar sizes are driven by df2, consider the following:
df2 = pd.DataFrame(np.mgrid[0:15, 0:10][0])
The result is then:
Upvotes: 4