Random Hex Color Bar Chart with Seaborn Catplot

  • Share this:

Code introduction


This function uses Seaborn's catplot to draw a bar chart, with the color of the points being a randomly generated hex color.


Technology Stack : Packages and technologies used in the code[English]

Code Type : The type of code

Code Difficulty : Intermediate


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

def random_hex_color():
    """
    Generates a random hex color code.
    """
    return "#{:06x}".format(np.random.randint(0, 0xFFFFFF))

def plot_random_distribution(data, x, y, hue):
    """
    Plots a random distribution using Seaborn's catplot with a hex color for the points.
    """
    # Generate a random hex color
    color = random_hex_color()
    
    # Create a categorical plot
    sns.catplot(x=x, y=y, hue=hue, data=data, kind="bar", palette=[color])
    
    plt.show()

# Example usage
data = sns.load_dataset("tips")
plot_random_distribution(data, "day", "total_bill", "sex")