Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

seaborn ignores custom color palette when number of patches exceeds number of colors

I set up a palette containing just black and gray as follows.

import seaborn as sns
sns.set_palette(['#000000', '#ABABAB'])

This works fine if I just have two or less patches in my plot.

sns.barplot([1, 2], [3, 4])

However, when I have more bars than colors, seaborn switches back to the default palette.

sns.barplot([1, 2, 3], [4, 5, 6]) 

Can I make seaborn cycle through my custom color palette? In the case above, the first bar should be black, the second grey and the third one black again.

My current workaround is

sns.set_palette(['#000000', '#ABABAB']*1000)

but I doubt this is the standard way to do it.

like image 658
actual_panda Avatar asked Feb 03 '26 11:02

actual_panda


1 Answers

It is quite simple as per the official docs. Just set n_colors to be more than the number of colors in the palette. Below is the relevant information (highlighted in bold). Here you can just set n_colors to a large number. Anything more than 2 will work in your case.

n_colors : int, optional Number of colors in the palette. If None, the default will depend on how palette is specified. Named palettes default to 6 colors, but grabbing the current palette or passing in a list of colors will not change the number of colors unless this is specified. Asking for more colors than exist in the palette will cause it to cycle.

import seaborn as sns
sns.set_palette(['#000000', '#ABABAB'], n_colors=100)

sns.barplot([1, 2, 3], [4, 5, 6]) 

EDIT It seems that one has to have to n_colors also more than the number of patches (bars in this case). So if there are two colors in the palette and 4 patches, then n_colors should be also more than both (>4 in this case).

enter image description here

like image 128
Sheldore Avatar answered Feb 06 '26 00:02

Sheldore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!