To enhance the aesthetics of the count plot we initially created with plot_categorical_vs_dummy, we can make several improvements, including adjusting colors, adding grid lines, modifying the font sizes, and positioning the legend in a better way. Let's update the function to make the graph look more visually appealing:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def plot_categorical_vs_dummy(dataframe, categorical_var, dummy_var):
"""
Plots a count plot of a categorical variable against a dummy variable,
with enhanced aesthetics.
Parameters:
dataframe (pd.DataFrame): The input DataFrame containing data.
categorical_var (str): The name of the categorical variable column.
dummy_var (str): The name of the dummy variable column (binary).
Returns:
None: Displays a count plot.
"""
# Input validation
if categorical_var not in dataframe.columns:
raise ValueError(f"{categorical_var} is not a column in the DataFrame")
if dummy_var not in dataframe.columns:
raise ValueError(f"{dummy_var} is not a column in the DataFrame")
# Set the aesthetic style of the plots
sns.set(style="whitegrid")
# Create a figure and axes object
plt.figure(figsize=(12, 7))
# Create the count plot
ax = sns.countplot(data=dataframe, x=categorical_var, hue=dummy_var,
palette="Set2", edgecolor=".2")
# Title and labels
plt.title(f'Count of {categorical_var} by {dummy_var}', fontsize=16)
plt.xlabel(categorical_var, fontsize=14)
plt.ylabel('Count', fontsize=14)
# Adding annotations on bars
for p in ax.patches:
ax.annotate(format(p.get_height(), '.0f'),
(p.get_x() + p.get_width() / 2, p.get_height()),
ha='center', va='bottom',
fontsize=12, color='black',
rotation=0,
xytext=(0, 5), # 5 points vertical offset
textcoords='offset points')
# Customize the legend
plt.legend(title=dummy_var, title_fontsize='13', fontsize='12', loc='upper right')
# Rotate x-axis labels for better readability
plt.xticks(rotation=45)
plt.tight_layout()
# Show the plot
plt.show()
# Example usage with a sample DataFrame
# df = pd.DataFrame({
# 'category': ['A', 'B', 'A', 'C', 'B', 'C', 'A', 'B'],
# 'dummy': [1, 0, 1, 0, 1, 0, 0, 1]
# })
# plot_categorical_vs_dummy(df, 'category', 'dummy')
Improvements Made:
-
Aesthetic Style: Set the style to whitegrid using sns.set(style="whitegrid"), which adds a nice grid background to the plot.
-
Figure Size: Increased the figure size for better visibility (plt.figure(figsize=(12, 7))).
-
Color Palette: Used a different color palette (Set2) for a more aesthetically pleasing look.
-
Annotations: Added annotations on top of the bars to display the count values clearly.
-
Improved Legend: Customized the legend's font size and position for clarity.
-
Font Sizes: Increased font sizes for titles and labels for better readability.
-
Rotation of x-axis Labels: Kept the rotation of x-axis labels for better visibility when there are many categories.
-
Tight Layout: Used plt.tight_layout() to ensure that the layout does not overlap and looks well-organized.
You can use the last part of the code (commenting out the df DataFrame setup and the function call) to test this updated function against real data. This function should provide a visually appealing representation of your categorical vs. dummy variable analysis!