Search code examples
pythonpandasdataframefunctionplotly

Plotly table cell color depending on cell data


Good day everyone, please can i be assisted in anyway possible. I am trying to code cell colour depending on the answer to my functions.

b = df['Supertrend']

a = b[-1]

def main(a):
   if a !=True:
   return 'Bearish'
   else:
   return 'Bullish'

poes = main(a)

j = d1['Supertrend']

k = j[-1]

def main(k):
   if k!= True:
   return 'Bearish'
   else:
   return 'Bullish'

doos = main(k)

l = d15['Supertrend']

m = l[-1]

def main(m):
  if m!= True:
  return 'Bearish'
  else:
  return 'Bullish'

naai = main(m)

n = d1h['Supertrend']

o = n[-1]

 def main(o):
  if o!= True:
  return 'Bearish'
  else:
  return 'Bullish'

tiet = main(o)

q = d1d['Supertrend']

p = q[-1]

 def main(p):
  if p!= True:
  return 'Bearish'
 else:
  return 'Bullish'

kak = main(p)

TF = ['1 Minute', '5 Minutes', '15 Minutes', '1 Hour', 'Daily']
BB = [doos, poes, naai, tiet, kak]

fig = go.Figure(data=[go.Table(
header=dict(values=[['<b>Timeframe</b>'], ['<b>Bullish/Bearish</b>']],
            line_color='black',
            fill_color='black',
            align='center',
            height= 40,
            font=dict(color='white', size=15)),

So i guess here is where I need some help. To dictate that if the function outputs bearish the cell must be red and if it outputs bullish it should be green

cells=dict(values=[TF,BB],
           line_color='darkslategray',
           fill = dict(color=['black', 

I tried the first below but doesnt really work

          ['#ff2d5d' if BB == str('Bearish') else '#04b29b']]),
           font=dict(color='white', size=12),
           height = 30,
           align='center'))
           ])

          fig.update_layout(width=500, height=450)
          fig.show()

Solution

  • Since if statements cannot be written in the list, it is possible to create a color list in advance and specify it to color-code the cells.

    TF = ['1 Minute', '5 Minutes', '15 Minutes', '1 Hour', 'Daily']
    BB = [doos, poes, naai, tiet, kak]
    
    colors = ['#ff2d5d' if c == 'Bearish' else '#04b29b' for c in BB]
    print(colors)
    fig = go.Figure(data=[go.Table(
        header=dict(values=[['<b>Timeframe</b>'], ['<b>Bullish/Bearish</b>']],
                    line_color='black',
                    fill_color='black',
                    align='center',
                    height= 40,
                    font=dict(color='white', size=15)),
    
       cells=dict(values=[TF,BB],
               line_color='darkslategray',
               fill = dict(color=['black',colors]),
               font=dict(color='white', size=12),
               height = 30,
               align='center'))
               ])
    
    fig.update_layout(width=500, height=450)
    fig.show()
    

    enter image description here