You are on page 1of 3

The code you provided is grouping the DataFrame df by the columns "Prefix" and

"Survived," counting the occurrences, and then creating a stacked bar chart for the

top five combinations with the highest count of "Survived" equal to 1. Here's the

labelled version of your code:

python
Copy code

import matplotlib.pyplot as plt

# Group the DataFrame by "Prefix" and "Survived," count occurrences, unstack,

fill NaN with 0, and sort by "Survived" equal to 1 in descending order

result = df.groupby(["Prefix",

"Survived"]).size().unstack(fill_value=0).sort_values(by=1,

ascending=False).head()

# Create subplots with 2 rows, 3 columns, and a figure size of (12, 8)

fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(12, 8))

# Iterate over each category and its corresponding axis

for i, (category, ax) in enumerate(zip(result.index, axes.flatten())):

# Extract data for the current category

category_data = result.loc[[category]]
# Plot a stacked bar chart on the current axis

category_data.plot(kind='bar', stacked=True, ax=ax)

# Set title, x-axis label, y-axis label, and legend for the current axis

ax.set_title(f'Category {category}')

ax.set_xlabel('Prefix')

ax.set_ylabel('Count')

ax.legend(title='Prefix')

# Adjust layout for better spacing

plt.tight_layout()

# Display the plot

plt.show()

Save to grepper
This code creates a 2x3 grid of subplots, where each subplot represents a category.

It then iterates through the categories, extracts the data for each category, and plots

a stacked bar chart on the corresponding subplot. The titles, labels, and legends are

set for each subplot, and the layout is adjusted for better spacing before displaying

the plot.

You might also like