Home > Software engineering >  Seaborn plot with colorbar, centered around 0
Seaborn plot with colorbar, centered around 0

Time:10-30

I am trying to change the default behaviour of seaborn by adding a colormap (a continuous color palette) instead of using the hue argument, which creates bins from a continuous variable. I have found the following code to work, however, I would like to add one more option, to center the color bar at 0, that is 0 gets the color white, and the colors diverge from zero to negative/positive.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

y=np.random.normal(30,30,100)
x=np.random.uniform(0,50,100)

s=sns.scatterplot(
    y=y,
    x=x,
    hue=y,
    size=y,
    palette='RdBu',
    sizes=(50,50)
)
norm=plt.Normalize(y.min(),y.max())
sm=plt.cm.ScalarMappable(cmap="RdBu",norm=norm)
sm.set_array([])
s.get_legend().remove()
s.figure.colorbar(sm)

enter image description here

As can be seen from the image 0 gets a slightly reddish color, because the data is not symmetric about zero. How can I center the colormap around 0? I am completely fine with an inflated colormap from say -80 to 80 (because of the asymmetry) if the center is at 0.

CodePudding user response:

Using the c, norm, and cmap key-word arguments which are passed through from seaborn to enter image description here

  • Related