I have a list of hex values representing different colors.
How can I represent those hex values in a grid of colors. That is, visualizing the color of each hex value.
Thanks.
With seaborn
the most straightforward way would probably be using 'sns.palplot()', for example:
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)
(credit to this answer for the hex_to_rgb()
function).
This will result in a single row of colored squares.
To split it into multiple rows, in case there are many entries, one could simply call sns.palplot()
multiple times, but that would result in a odd layout since the space between the rows would be larger that the space between columns, for example:
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)
The other option could be mimicking what sns.palplot()
does (see source code) and create sub plots:
# 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([])
Hope this helps.