Fabian Bosler
Fabian Bosler

Reputation: 2510

Add an additional axes to seaborn heatmap

I have a retention matrix as a seaborn heatmap. I was wondering, where and how I could add an additional axis. I want to have an additional vertical bar chart next to the heatmap to show the number of new users in a given cohort. Any help or pointers would be much appreciated.

I tried using fig.add_axes, but am somewhat lost as to what parameters and what values to use. Cheers

parameter = 'Total Rent'
recordtpye = 'Tenant'

dataset = df[(df['Account Record Type'] == recordtpye)]
grouped = dataset.groupby(['TenanatCohort','BookingPeriod'])

cohorts = grouped.agg({'Request ID': pd.Series.nunique,'Total Rent':np.sum})
cohorts.rename(columns={'Request ID': 'Number of Bookings'}, inplace=True)
cohorts.reset_index(inplace=True)
cohorts.set_index(['TenanatCohort', 'BookingPeriod'], inplace=True)

cohort_group_size = dataset.groupby('TenanatCohort').agg({'Tenant: Account Name': pd.Series.nunique})

user_retention_numbers = cohorts[parameter].unstack(0)

bookings_per_cohort = \
cohorts.reset_index()\
.groupby('TenanatCohort')\
.agg({parameter: np.sum})[parameter]\
.divide(cohort_group_size['Tenant: Account Name'])

inp = user_retention_numbers

sns.set(style='white')

fig = plt.figure(figsize=(16,7))

graph = sns.heatmap(inp.T,
                    mask=inp.T.isnull(),
                    cmap="Blues",
                    annot=True,
                    fmt=".0f",
                    annot_kws={"size":10});
graph.set_xlabel("Booking Period")
graph.set_ylabel("Cohort Group")

plt.yticks(rotation=0)

Upvotes: 0

Views: 1045

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40747

seaborn's heatmap is an axis level function, meaning that you can create whatever axes you want beforehand, and pass a reference to the Axes object you want seaborn to use when calling heatmap.

uniform_data = np.random.rand(10, 12)
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(6,4), gridspec_kw={'width_ratios':(5,1)})
sns.heatmap(uniform_data, ax=ax1)
ax2.plot([1,2],[3,4], 'ro-')

enter image description here

Upvotes: 1

Related Questions