Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random Colors in Bar chart with Plotly Python

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)
like image 537
Sumedha Nagpal Avatar asked Jan 27 '23 03:01

Sumedha Nagpal


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

like image 89
Doston Avatar answered Feb 17 '23 09:02

Doston