【发布时间】:2020-02-12 16:49:45
【问题描述】:
我有一个代表不同颜色的十六进制值列表。
如何在颜色网格中表示这些十六进制值。即可视化每个十六进制值的颜色。
谢谢。
【问题讨论】:
我有一个代表不同颜色的十六进制值列表。
如何在颜色网格中表示这些十六进制值。即可视化每个十六进制值的颜色。
谢谢。
【问题讨论】:
对于seaborn,最直接的方法可能是使用'sns.palplot()',例如:
import seaborn as sns
sns.set()
def hex_to_rgb(hex_value):
h = hex_value.lstrip('#')
return tuple(int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4))
hex_colors = [
'#f0787e', '#f5a841', '#5ac5bc', '#ee65a3', '#f5e34b', '#640587', '#c2c36d',
'#2e003a', '#878587', '#d3abea', '#f2a227', '#f0db08', '#148503', '#0a6940',
'#043834', '#726edb', '#db6e6e', '#db6ecb', '#6edb91'
]
rgb_colors = list(map(hex_to_rgb, hex_colors))
sns.palplot(rgb_colors)
(感谢this answer hex_to_rgb() 函数)。
这将产生单行彩色方块。
要将其拆分为多行,以防有很多条目,可以简单地多次调用sns.palplot(),但这会导致布局奇怪,因为行之间的空间会大于列之间的空间,例如:
row_size = 5
rows = [rgb_colors[i:i + row_size] for i in range(0, len(rgb_colors), row_size)]
for row in rows:
sns.palplot(row)
另一种选择可能是模仿sns.palplot() 所做的事情(参见source code)并创建子图:
# Make sure the last row has the same number of elements as the other ones by
# filling it with a default color (white).
rows[-1].extend([(1.0, 1.0, 1.0)] * (row_size - len(rows[-1])))
num_rows = len(rgb_colors) // row_size + 1
f, plots = plt.subplots(num_rows, 1)
plt.subplots_adjust(hspace=0.0)
for i in range(num_rows):
plot = plots[i]
plot.imshow(np.arange(row_size).reshape(1, row_size),
cmap=mpl.colors.ListedColormap(rows[i]),
interpolation="nearest", aspect="auto")
plot.set_xticks(np.arange(row_size) - .5)
plot.set_yticks([-.5, .5])
plot.set_xticklabels([])
plot.set_yticklabels([])
希望这会有所帮助。
【讨论】:
如果您有 n x m 颜色列表,您可以转换为 rgba 并重新调整为 (m, n, 4)。例如。对于列表中的 6x5=30 十六进制值:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba_array
list_of_hex = [f"#{''.join(np.random.choice(list('0123456789abcdef'), size=6))}" \
for _ in range(30)]
plt.imshow(to_rgba_array(list_of_hex).reshape(6,5,4))
plt.show()
【讨论】: