Plot two Seaborn sns.kdeplot figures on same plot space but each with a different colorbar with same range

Viewed 863

I have been trying this for several hours now.

I am essentially trying to get the scales of the colorbars to be the same.

I picked up this example from a previous post in which one suggestion was to use the kwargs = {'levels': np.arange(0, 0.15, 0.01)} line. I have included it, but I have not seen any changes, the scales remain the same.

This is the code that I am using:

import numpy as np
import seaborn as sns
import pandas
import matplotlib.pyplot as plt
from matplotlib import rcParams


np.random.seed(10)
sns.set(color_codes=True)

rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Arial']

plt.ioff()
kwargs = {'levels': np.arange(0, 0.15, 0.01)} #trying to get the colorbar scales to be the same
f, ax = plt.subplots(figsize=(7, 5))
ax.tick_params(axis='both', which='major', labelsize=22)

mean, cov = [0, 2], [(2, 1), (.5, 1)]
x1, y1 = np.random.multivariate_normal(mean, cov, size=50).T

mean, cov = [5, 7], [(3, 2), (7, 1)]
x2, y2 = np.random.multivariate_normal(mean, cov, size=50).T

sns.kdeplot(x1, y1, cmap="Reds",   shade=True, shade_lowest=False,
             alpha=0.66, legend=False, cbar=True, **kwargs, ax= ax )
sns.kdeplot(x2, y2, cmap="Greens", shade=True, shade_lowest=False, alpha=0.66,\
                 legend=False, cbar=True,**kwargs, ax = ax)

plt.xlabel("foo", fontsize=22)
plt.ylabel("bar", fontsize=22)

I would really appreciate your helpenter image description here

1 Answers

With the clue from @mwaskom, this is the closest I managed to get to your expected outcome:

enter image description here

import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams


np.random.seed(10)
sns.set(color_codes=True)

rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Arial']

kwargs = {}
f, ax = plt.subplots(figsize=(7, 5))
ax.tick_params(axis='both', which='major', labelsize=22)

mean, cov = [0, 2], np.array([(2, 1), (.5, 1)])
x1, y1 = np.random.multivariate_normal(mean, cov, size=50).T

mean, cov = [5, 7],  np.array([(3, 2), (7., 1)])
x2, y2 = np.random.multivariate_normal(mean, cov, size=50).T


x = np.concatenate((x1, x2))
y = np.concatenate((y1, y2))
class_labels = ['class 1']*len(x1) + ['class 2']*len(x2)
df = pd.DataFrame({
    'x': x,
    'y': y,
    'class': class_labels,
})

palette = {
    'class 1' : 'Red',
    'class 2': 'Green',
}

sns.kdeplot(x='x', y='y', data=df, hue='class', palette=palette, shade=True, thresh=0.05,
             alpha=0.66, legend=False, cbar=True, **kwargs, ax= ax)

plt.xlabel("foo", fontsize=22)
plt.ylabel("bar", fontsize=22)
Related