How to define a colors with rgb values in the seaborn objects api?

Question:

I want to color my dots in a scatterplot with some rgb values.

Using the original api, this is easy:

import seaborn as sns
x = [0, 1, 2]
y = [0, 0, 0]
colors = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
sns.scatterplot(x=x, y=y, c=colors)

I get a red, a green and a blue dot.

But how do you do this with the objects api?

import seaborn.objects as so
so.Plot(x=x, y=y).add(so.Dot()).scale(color=colors)

This doesnt work. Depending where you put the color argument you get different error messages.

Edit:
The end result looks something like this. Some 3d coordinates represented as rgb values.

enter image description here

The solution with the hex colors works fine

hex_colors = [mpl.colors.rgb2hex(c) for c in colors]
so.Plot(x=x, y=y, color=hex_colors).add(so.Dot()).scale(color=None)

Only that Vscode tells me the types are incompatible:

Argument of type "list[str]" cannot be assigned to parameter "color" of type "VariableSpec" in function "__init__"
Argument of type "None" cannot be assigned to parameter "color" of type "Scale" in function "scale"

Asked By: Sandro Martens

||

Answers:

I assume you want the colors to map to the x positions

so.Plot(x=x, y=y, color=x).add(so.Dot(), legend=None).scale(color=colors)

enter image description here

You can also use an identity scale:

so.Plot(x=x, y=y, color=colors).add(so.Dot()).scale(color=None)

But the variables are documented as taking a vector argument, not a matrix, so I am not sure I’d expect this to always work in the future. Using hex values may be more robust:

hex_colors = [mpl.colors.rgb2hex(c) for c in colors]
so.Plot(x=x, y=y, color=hex_colors).add(so.Dot()).scale(color=None)

enter image description here

Answered By: mwaskom
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.