How to use a second dataframe of the same size to determine the color of the heatmap cells

Question:

If I have two DataFrames that have the same x and y axis, how can I plot the values of the df1 on a seaborn heatmap style grid, but have the colors of each cell correspond to the values in the df2?

Here are the two heatmaps that I want to combine into a single heatmap:

Heatmap for df1

Heatmap for df1

Heatmap for df2

Heatmap for df2

I have tried to base the cmap off df2 but the colors still seem to be related to the df1.

Asked By: Aidan24

||

Answers:

You can call sns.seaborn(data=dataframe_for_color, annot=dataframe_for_texts, ...).

Here is an example, using the number of passengers to fill in the annotations, and a coloring scheme based on year and month values:

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

flights = sns.load_dataset('flights')
passengers = flights.pivot(index='year', columns='month', values='passengers')

coloring_np = np.fromfunction(lambda year, month: (year % 4) * 12 + (month * 7) % 12, passengers.shape, dtype=int)
coloring_df = pd.DataFrame(coloring_np, index=passengers.index, columns=passengers.columns)

ax = sns.heatmap(data=coloring_df, annot=passengers, fmt='.0f', cmap='turbo', cbar=False)
plt.show()

seaborn heatmap with coloring from other dataframe

Answered By: JohanC
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.