根据值更改条形图颜色

时间:2020-08-15 22:30:25

标签: python plotly bar-chart

我有以下数据: 8,518,000 27,525,000 20,532,000 12,897,000 (27,858,000) (5,266,000) (18,442,000) (78,850,000) (43,813,000) (26,920,000) (4,501,000) (19,619,000) (12,938,000) 前四年为正数,后9年为负数。

对于我的绘图条形图,我希望颜色在正时为黑色,在负时为红色。着色的最简单方法是什么?

现在我已将一切都设置为带有marker_color ='red'的红色,但是marker_color [0:3] ='black'会导致错误。

1 个答案:

答案 0 :(得分:0)

您的问题尚不清楚,但是如果我对您的理解正确,则可以为每个数据点创建颜色列表,然后将该颜色列表的字典传递给marker参数。

import plotly.graph_objects as go

y = [8510000, 27525000, 20532000, 12897000, 
27858000, 5266000, 18442000, 78850000, 43813000, 26920000, 4501000, 19619000, 12938000]
# colors list with first 4 set to 'black', last 9 set to 'red'
colors = ['black']*4 + ['red']*9

data = [dict(type='bar',
    y=y,
    marker=dict(color=colors)
)]

fig = go.Figure(data=data)
fig.show()

enter image description here