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

Sum*_*pal 4 python python-3.x plotly

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

条形图 在此处输入图片说明

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

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

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)
Run Code Online (Sandbox Code Playgroud)

小智 6

这是我本周一直面临的问题,我用 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))
Run Code Online (Sandbox Code Playgroud)

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