gpt4 book ai didi

python - 使用 Plotly Python 在条形图中生成随机颜色

转载 作者:行者123 更新时间:2023-12-01 08:42:42 28 4
gpt4 key购买 nike

我正在使用 Plotly for Python 生成一些堆积条形图。由于我有 17 个堆叠的对象,条形的颜色开始重复,如下图所示。

Bar Chart enter image description here

有人可以告诉我如何为每个堆栈获取独特的颜色吗?

请找到我的代码来生成下面的条形图:

import plotly
plotly.tools.set_credentials_file(username='xxxxxxxx',
api_key='********')
dd = []
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np


for k,v in new_dict.items():

trace = go.Bar(x = x['unique_days'],
y = v,
name = k,
text=v,
textposition = 'auto',
)
dd.append(trace)




layout= go.Layout(
title= 'Daily Cumulative Spend per campaign',
hovermode= 'closest',
autosize= True,
width =5000,
barmode='stack',
xaxis= dict(
title= 'Date',
zeroline= False,
gridwidth= 0,
showticklabels=True,
tickangle=-45,
nticks = 60,
ticklen = 5
),
yaxis=dict(
title= 'Cumulative Spend($)',
ticklen= 5,
gridwidth= 2,
),
showlegend= True
)
fig = dict(data=dd, layout = layout)

py.iplot(fig)

最佳答案

这是我这周遇到的问题,我用 Matplotlib 模块解决了。这是我的代码:

import matplotlib, random

hex_colors_dic = {}
rgb_colors_dic = {}
hex_colors_only = []
for name, hex in matplotlib.colors.cnames.items():
hex_colors_only.append(hex)
hex_colors_dic[name] = hex
rgb_colors_dic[name] = matplotlib.colors.to_rgb(hex)

print(hex_colors_only)

# getting random color from list of hex colors

print(random.choice(hex_colors_only))

列表中有 148 种颜色,您可以将此列表与您的愿望结合起来。希望它对某人有用:)

关于python - 使用 Plotly Python 在条形图中生成随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53436786/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com