How to Annotate Bars in Grouped Barplot in Python?
0 728
Enhancing Grouped Bar Plots: Adding Annotations in Python
Grouped bar plots are invaluable for comparing multiple categories across different groups. However, to make these plots more informative, it's essential to annotate each bar with its respective value. In this guide, we'll explore how to achieve this using Python's Matplotlib and Seaborn libraries.
Understanding the Dataset
We'll utilize the Titanic dataset, which is readily available in the Seaborn library. This dataset provides information about passengers, including their age, class, and sex. Our goal is to visualize the average age of passengers across different ticket classes and sexes.
import seaborn as sns
import matplotlib.pyplot as plt
# Load the Titanic dataset
df = sns.load_dataset("titanic")
Preparing the Data
To create a grouped bar plot, we need to aggregate the data. We'll group the dataset by 'sex' and 'class', calculating the average age and the count of passengers in each group.
# Grouping and aggregating the data
data_df = df.groupby(['sex', 'class']).agg(
avg_age=('age', 'mean'), count=('sex', 'count')).reset_index()
Creating the Grouped Bar Plot
With the data prepared, we can now create a grouped bar plot using Seaborn's barplot() function. We'll set 'class' on the x-axis, 'avg_age' on the y-axis, and use 'sex' to differentiate the bars.
# Plotting the grouped bar plot
plt.figure(figsize=(8, 6))
sns.barplot(x="class", y="avg_age", hue="sex", data=data_df, palette='Greens')
plt.ylabel("Average Age", size=14)
plt.xlabel("Ticket Class", size=14)
plt.title("Grouped Barplot with Annotations", size=18)
Annotating the Bars
To add annotations, we can use the ax.annotate() method. This method allows us to place text labels at specific positions on the plot. We'll iterate over each bar, calculate its height, and position the annotation accordingly.
# Annotating the bars
for p in plt.gca().patches:
height = p.get_height()
plt.gca().annotate(f'{round(height)} years',
(p.get_x() + p.get_width() / 2., height),
ha='center', va='center',
xytext=(0, 9),
textcoords='offset points',
fontsize=12, color='black')
Final Touches
After adding the annotations, it's a good practice to adjust the layout to ensure everything fits neatly. We can use plt.tight_layout() for this purpose.
# Adjusting the layout
plt.tight_layout()
# Displaying the plot
plt.show()
By following these steps, we've successfully created a grouped bar plot with annotations, providing a clear and informative visualization of the Titanic dataset.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments