简体   繁体   中英

Change bar color based on value

I am currently using plotly to generate some simple graphs in python. The graphs represent the predicted energy consumption of a large area each hour. What i want to do is change the color of each individual bar if the predicted energy consumption of that area is high to red, and if it is low to green. The high- and low-values are calculated for each day, so they are not constant. Is there any way i could do this using plotly?

Seemed like a fun task to practice plotly and python on.

Here is a plotly plot using some faked up data:

import plotly.plotly as py
import plotly.graph_objs as go
import random
import datetime

# setup the date series
#  we need day of week (dow) and if it is a weekday (wday) too
sdate = datetime.datetime.strptime("2016-01-01", '%Y-%m-%d').date()
edate = datetime.datetime.strptime("2016-02-28", '%Y-%m-%d').date()
ndays = (edate - sdate).days + 1  
dates = [sdate + datetime.timedelta(days=x) for x in range(ndays)]
dow   = [(x + 5) % 7 for x in range(ndays)]
wday  = [1 if dow[x]<=4 else 0 for x in range(ndays)]

# now some fake power consumption 
# weekdays will have 150 power consumption on average
# weekend will have 100 power consumption on average
# and we add about 20 in random noise to both
pwval  = [90 + wday[x] * 50 + random.randrange(0, 20) for x in range(ndays)]
# limits - higher limits during the week (150) compared to the weekend (100)
pwlim  = [150 if dow[x] <= 4 else 100 for x in range(ndays)]

# now the colors
clrred = 'rgb(222,0,0)'
clrgrn = 'rgb(0,222,0)'
clrs  = [clrred if pwval[x] >= pwlim[x] else clrgrn for x in range(ndays)]

# first trace (layer) is our power consumption bar
trace0 = go.Bar(
    x=dates, 
    y=pwval,
    name='Power Consumption',
    marker=dict(color=clrs)
)
# second trace is our line showing the power limit
trace1 = go.Scatter( 
    x=dates,
    y=pwlim,
    name='Power Limit',
    line=dict(
        color=('rgb(0,0,222)'),
        width=2,
        dash='dot')
)
data = [trace0, trace1]
layout = go.Layout(title='Power')
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='power-limits-1')

And this is what it looks like:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM