繁体   English   中英

根据值更改条形颜色

[英]Change bar color based on value

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

似乎是一个有趣的任务来练习 plotly 和 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')

这就是它的样子:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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