根据值更改条形颜色

时间:2017-03-25 01:05:37

标签: python bar-chart plotly

我目前正在使用plotly在python中生成一些简单的图形。 图表表示每小时大面积的预测能量消耗。我想要做的是,如果该区域的预测能耗高至红色,并且低至绿色,则更改每个条形的颜色。每天计算高值和低值,因此它们不是恒定的。 有什么方法可以用剧情来做到这一点吗?

1 个答案:

答案 0 :(得分:3)

看起来像是一个有趣的任务来练习剧情和python。

这是使用一些伪造数据的情节图:

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')

这就是它的样子:

enter image description here