Random Heatmap Generation with Random Feature Subset and HSV Palette

  • Share this:

Code introduction


This function takes a DataFrame as input, randomly selects 20 features from it, generates a heatmap, the color mapping of the heatmap is based on a random palette from the HSV color space, and the center value of the heatmap is 0. The numbers in the heatmap represent the correlation between features.


Technology Stack : seaborn, numpy, matplotlib, pandas

Code Type : Function

Code Difficulty : Intermediate


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

def random_heatmap(data):
    """
    Generates a random heatmap from a given DataFrame.
    """
    # Select a random subset of the DataFrame
    random_subset = data.sample(n=20)
    
    # Generate a random color palette
    palette = sns.color_palette("hsv", n_colors=20)
    
    # Create the heatmap
    sns.heatmap(random_subset.corr(), cmap=palette, center=0, annot=True)
    
    plt.show()

# Sample DataFrame for demonstration
np.random.seed(0)
sample_data = np.random.rand(100, 10)
sample_df = pd.DataFrame(sample_data, columns=[f"Feature_{i}" for i in range(10)])

# Call the function with the sample DataFrame
random_heatmap(sample_df)