Is there a way to pass a column of hex codes into Matplotlib/seaborn?

Viewed 54

Given I have a df with 4 columns, such that:

x = [1,3,6,8]
y = [7,4,8,7]
names = ['eggs','eggs','spam','spam']
hex = ['#76BB76','#76BB76','#7B8BFC','#7B8BFC']

where each element in names has a corresponding code in the 'hex' column.

So far I have been able to group the points using the names column like:

fg = seaborn.FacetGrid(data=df, hue='names')
fg.map(plt.scatter, 'x', 'y').add_legend()

Here I could use 'hex' instead of 'names' as they are grouped the same way.

However, this generates a plot where I can color the points using an existing cmap (eg cmap='viridis'). I would like to assign the points a custom color that I have in the hex column as this will improve the appearance of the plot. Is there an easy way to do this in matplotlib/seaborn?

1 Answers

In this case I would just use matplotlib's scatter() with the c param:

fig, ax = plt.subplots()
for name, data in df.groupby('names'):
    ax.scatter(data.x, data.y, c=data.hex, label=name)
ax.legend(title='name')

matplotlib groupby scatter

Related