【问题标题】:Mathplotlib set plot color based on an object idMatplotlib 根据对象 id 设置绘图颜色
【发布时间】:2021-07-21 11:52:01
【问题描述】:

我有一些带有一些数据的 python 对象,它们都有一个 id (1,2,3,4,5 ..... n)。我有一个 python 函数,我在其中发送这些对象之一,我想从中绘制数据,并根据 id 绘制不同的颜色。我尝试做一些我从其他问题中看到的事情,例如尝试将 id 整数转换为 RGB 值,如下所示:

Blue =  integer & 255
Green = (integer >> 8) & 255
Red =   (integer >> 16) & 255

return (RED/255, Green/255, Blue/255)  # to get them into [0,1] interval

但问题在于,1、2、3 之类的接近数字之间的颜色将相同(基本上几乎具有相同的颜色)。有什么办法吗?

编辑:

所以我正在考虑做这样的事情:

def rgb_function(object_id):
    
    random.seed(object_id)
    value = random.uniform(0,1)
    #then calculate RGB value based on this answer: https://stackoverflow.com/questions/55178857/convert-a-floating-point-number-to-rgb-vector
     H = value;
     R = abs(H * 6 - 3) - 1;
     G = 2 - abs(H * 6 - 2);
     B = 2 - abs(H * 6 - 4);  
     return max(0, min(1, R)), max(0, min(1, G)), max(0, min(1, B))

     

【问题讨论】:

  • n 有多大?
  • 这取决于根据某些标准要创建多少个对象,我会说平均大约 600 个,但它有点动态

标签: python matplotlib rgb


【解决方案1】:

您可能只需使用多种颜色对颜色图进行洗牌,使其随机化即可。

import random
import matplotlib.pyplot as plt
import numpy as np

colors = [plt.cm.hsv(i) for i in np.linspace(0, 1, 600)]
# random.seed(77) # uncomment this if you want the same colors everytime
random.shuffle(colors)

fig, ax = plt.subplots()
ax.plot(range(20), range(20), colors[:20]

# this gives different colors for ids that are similar

如果您想要真正随机的颜色,您应该看到this 答案。但也许这有点过头了。

【讨论】:

  • 感谢 krm 的回答,我做了一些不同的事情,在 [0, 1] 之间生成一个随机浮点数,然后计算 RGB 值(请参阅我的编辑),你认为这样的事情是否正确?
  • 您对 LGTM 的更改。这肯定会产生不同的颜色。
  • 是的,我想我会遇到的另一个问题是有时生成的颜色太亮了,例如生成了亮黄色,当我用那种颜色绘制点时,它们有点难查看。有什么办法可以降低亮度?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多