I have this dataframe with True
and False
values with a heatmap plot:
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap
df = pd.DataFrame({'A': {1: False, 2: False, 3: False, 4: True, 5: True, 6: True, 7: False, 8: False},
'B': {1: False, 2: False, 3: True, 4: True, 5: False, 6: True, 7: True, 8: False},
'C': {1: False, 2: True, 3: False, 4: False, 5: False, 6: False, 7: True, 8: True}})
fig, ax = plt.subplots(figsize=(3,3))
cmap = sns.mpl_palette("Set2", 2)
sns.heatmap(data=df, cmap=cmap, cbar=False)
plt.xticks(rotation=90, fontsize=10)
plt.yticks(rotation=0, fontsize=10)
plt.show()
I'm trying to add outside the plot a simple legend where the red color = True
and the green color = False
, with labels "missing value" when is red, and "non missing value" when is green. I'm not looking for a continuous legend as its common on heatmaps (that's why cbar=False
).
I have tried multiple solutions (from other plots also) without success: how to add a legend, legend guide, matplotlib legends not working, customizing plot legends, among others, but all of them are too far complicated to adapt them to heatmap. I'm looking for something like:
plt.legend(values=[1,0], colors=["red", "green"], label_legend=["missing value", "non missing value"])
Any suggestions?