使用 Plotly Python 在条形图中生成随机颜色 [英] Generate random Colors in Bar chart with Plotly Python

查看:117
本文介绍了使用 Plotly Python 在条形图中生成随机颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

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

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

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

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

这篇关于使用 Plotly Python 在条形图中生成随机颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆