Generate random Colors in Bar chart with Plotly Python

Question:

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.

Bar Chart
enter image description here

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)
Asked By: Sumedha Nagpal

||

Answers:

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 🙂

Answered By: Doston

the same as above, short version:

import matplotlib, random
colors = dict(matplotlib.colors.cnames.items())
hex_colors = tuple(colors.values())
print(hex_colors)
#getting a random color from the dict
print(random.choice(hex_colors))
Answered By: Priscila Gutierres
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.