【问题标题】:Method to generate 'N' random colors 'P' times using get_cmap().colors. Error: 'LinearSegmentedColormap' object has no attribute 'colors'. Matplotlib使用 get_cmap().colors 生成“N”次随机颜色“P”次的方法。错误:“LinearSegmentedColormap”对象没有属性“颜色”。 Matplotlib
【发布时间】:2023-03-10 00:15:01
【问题描述】:

我正在尝试生成 N 个随机颜色 P 次。例如,我有 10 个不同的地块,每个地块有 20 个条,我想为每个条分配不同的颜色。如何为每个条生成 20 种随机颜色 10 次?

我已经编写了这段代码,但它显示错误。

def generate_n_random_cmap(how_many=20,list_len=10):
    '''
    Generate list of 20 colors 10 times by default. 
    NOTE: Colors can be duplicated if lit_len is greater than length of plt.colormap()
    '''
    import random
    import matplotlib.pyplot as plt
    c_list = []
    while len(c_list)!=list_len:
        try:
            c_list.append(plt.cm.get_cmap(random.choice(plt.colormaps()),how_many).colors)
        except :
            None
    return random.shuffle(c_list)

我得到的错误是:

'LinearSegmentedColormap' object has no attribute 'colors'

还有其他方法吗?颜色本质上应该是随机的。

【问题讨论】:

    标签: python python-3.x matplotlib seaborn


    【解决方案1】:

    有几件事。正如错误消息所说,您获得的对象没有属性颜色。正如manual 所说,Make a linear segmented colormap with name from a sequence of colors which evenly transitions from colors[0] at val=0 to colors[-1] at val=1.

    其次,您要做的是获得一个调色板列表。一种做你想做的事情的方法是让每个图表随机选择你想要的how_many颜色,然后相应地绘制你的条形图,例如:

    import numpy as np 
    import matplotlib.pyplot as plt 
    import matplotlib.colors as mcolors
    
    how_many = 20 
    # Create a list of colours randomly selected from the list of matplotlib colours
    c_list = [np.random.choice(list(mcolors.CSS4_COLORS.values())) for i in range(how_many)] 
    barlist=plt.bar(np.arange(len(c_list)), np.arange(len(c_list))) 
    for i in range(len(c_list)):
        barlist[i].set_color(c_list[i])
    

    您可以做的另一件事是生成不同的调色板,例如。使用 seaborn 甚至 matplotlib,您可以使用随机选择的调色板 np.random.choice(plt.colormaps())。相关信息可以在manual of seaborn 或那些帖子中找到: How to give a pandas/matplotlib bar graph custom colors, https://stackoverflow.com/a/18991446/12281892.

    【讨论】:

    • 我发现只有某些颜色图可以在循环中使用 try catch 产生超过 20 到一百万种不同的颜色。对于随机,我可以轻松地在 3 的元组中使用 random.random(),然后在 RGBA 中使用单个 1,但这不是我想要的。无论如何感谢您的帮助,以便我找到答案。
    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 2013-01-21
    • 2018-05-16
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2016-12-21
    相关资源
    最近更新 更多