You can download this code by clicking the button below.
This code is now available for download.
This function generates a bar plot using the seaborn library, randomly selects a palette, and allows the user to group the bars by different columns.
Technology Stack : seaborn, numpy, pandas, matplotlib
Code Type : The type of code
Code Difficulty :
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
def random_bar_plot(data, x, y, hue=None):
"""
Generate a random bar plot using seaborn.
Parameters:
- data: pandas DataFrame containing the data to plot.
- x: str, the name of the column to plot on the x-axis.
- y: str, the name of the column to plot on the y-axis.
- hue: str or list of str, the name(s) of the column(s) to use for grouping the bars.
"""
# Randomly choose a palette
palette = sns.color_palette(random.choice(['husl', 'muted', 'pastel', 'bright', 'dark']))
# Create a bar plot
sns.barplot(x=x, y=y, hue=hue, data=data, palette=palette)
# Set title and labels
plt.title('Random Bar Plot')
plt.xlabel(x)
plt.ylabel(y)
plt.show()
# Example usage:
# data = pd.DataFrame({
# 'Category': ['A', 'B', 'C', 'D'],
# 'Values': [10, 20, 15, 5],
# 'Subgroup': ['X', 'X', 'Y', 'Y']
# })
# random_bar_plot(data, 'Category', 'Values', 'Subgroup')