Consistent colour for a variable level

I am trying to see how I can assign a particular variable level to a specific colour in Plot. For example with the penguins dataset if I just have the Gentoo values and I plot, I get a blue marker:


But if I plot two levels (Adeline and Gentoo) I get two colours (which makes sense) but Gentoo is now orange. In the context of interactive content using Inputs this isn’t ideal because the colour marker will change depending on some user input.


So my question is, waht would be a good strategy to ensure that a variable level is always mapped to the same colour?

Here is my example notebook: consistent colours / Sam Albers | Observable

I think if you want to ‘fix’ the colors, you have to specify the domain and the range. Something like this:
color: { legend: true, domain: ["Adelie", "Gentoo"], range: ["#000000", "#FF0000"] },

1 Like

To add to what Cobus suggests, here are two other ways to do this:

  1. Make sure you have all the colors in the data, for example by using Plot’s filter transform instead of filtering the data
  2. Create a color scale outside of this plot (for example with a bar chart of all species), and reuse that bar chart’s color scale in the scatterplot.
1 Like

Wow. filter transform is :heart_eyes: . I opted for Cobus’s answer here because it my case it was the most parsimonious. But this is a really nice thing to know about.

To add, you just need to set the domain if you want a deterministic encoding. You only need to set the range if you don’t want to use the default color scheme.

1 Like