Generate random Colors in Bar chart with Plotly Python

妖精的绣舞 提交于 2021-02-19 02:23:47

问题


I am using Plotly for Python to generate some stacked bar charts. Since I have 17 objects which are getting stacked, the colour of the bars has started repeating as seen in the image below.

Can someone tell me how to get unique colours for each stack?

Please find my code to generate the bar chart below:

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)

回答1:


It was the issue which I have been facing in this week and I solved with Matplotlib module. Here is my code:

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))

There are 148 colors in the list and you can integrate this list with your wish. Hopefully it is useful for someone :)



来源:https://stackoverflow.com/questions/53436786/generate-random-colors-in-bar-chart-with-plotly-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!