Categorical Heatmap Generation with Seaborn and Hue Highlighting

  • Share this:

Code introduction


This function generates a categorical heatmap using seaborn, which can highlight values based on a specified color (hue). Each cell in the heatmap is colored according to the data value, and the highlighted values are colored based on the specified color map.


Technology Stack : seaborn, numpy, matplotlib.pyplot

Code Type : The type of code

Code Difficulty : Advanced


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

def plot_categorical_heatmap(data, x, y, hue, cmap='coolwarm'):
    """
    Generate a categorical heatmap using seaborn.
    """
    # Create a categorical heatmap
    sns.heatmap(data, xticklabels=data.columns, yticklabels=data.index, cmap=cmap, annot=True, fmt=".2f", cbar_kws={'label': 'Values'})
    
    # Highlight the values based on hue
    for i, j in zip(*np.triu_indices_from(data, k=1)):
        plt.text(j+0.5, i-0.3, data.iloc[i, j], ha='center', va='center', color='black')
        plt.text(j+0.5, i-0.7, hue[data.iloc[i, j]], ha='center', va='center', color='white', fontsize=10)

    plt.xlabel(x)
    plt.ylabel(y)
    plt.title('Categorical Heatmap with Hue')