根据值更改条形图颜色

2024-10-16 20:49:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用plotly在python中生成一些简单的图形。 这些图表表示每小时大面积的预计能耗。我要做的是改变每个单独的酒吧的颜色,如果预测的能量消耗是高到红色,如果它是低到绿色。每天都会计算高值和低值,因此它们不是常量。 我有没有办法用plotly来做这个?在


Tags: 图形颜色图表plotly酒吧常量小时绿色
1条回答
网友
1楼 · 发布于 2024-10-16 20:49:17

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

相关问题 更多 >