Search code examples
pandasseabornpalette

centre palette for plotting - Seaborn


I'm hoping to centre a seaborn palette using a diverting colormap. Specifically, I want zero to signify the divergence. However, may values aren't distributed evenly. So the min and max values aren't the same distance from 0. As such, the palette doesn't align. I'm still hoping to use the same palette colors but centre the divergence at 0.

df = pd.DataFrame({ 
    'Val' : ['A','A','A','A','A','A','A','A','A','A','A','A'],                  
    'A_1' : [-5, 2, 3, 4, 5, 7, 1, -4, -2, 6, -1, 0],                      
        })

g = sns.FacetGrid(df, 
                  col = 'Val', 
                  hue = 'A_1',                               
                  aspect = 1,
                  height = 5, 
                  palette = 'BrBG',
                  sharex = False)


g.map(sns.swarmplot, 'Val', 'A_1')

Solution

  • Unfortunately you can't do so directly.

    There is one workaround that should work fine: seaborn's diverging palette.

    It allows you to create a palette of your choice. You can choose to locate colors in such a way that will match exactly what you want.

    The example in the documentation is pretty good. Another great examples:

    Seaborn color palette: how to choose which part to center on (e.g. which end of the plot is red and which end is blue)?

    Creating a diverging color palette with a “midrange” instead of a “midpoint”