python 条形图指定颜色_根据值更改条形图颜色

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

它看起来是这样的:

0ZwIC.png