import numpy as np
import matplotlib.pyplot as plt
# Generate sample data
group_names = ['Group A', 'Group B', 'Group C']
category_names = ['Category 1', 'Category 2', 'Category 3', 'Category 4']
data = np.random.rand(len(group_names), len(category_names))
# Normalize the data within each category
category_totals = np.sum(data, axis=0)
normalized_data = data / category_totals[np.newaxis, :]
# Plot grouped bar charts
fig, ax = plt.subplots()
bar_width = 0.2
opacity = 0.8
colors = ['#4286f4', '#f44174', '#f4d641', '#41f45e']
for i, group_data in enumerate(normalized_data):
x = np.arange(len(category_names))
bars = ax.bar(x + i * bar_width, group_data, bar_width,
alpha=opacity, color=colors[i], label=group_names[i])
# Add percentage annotations for each bar
for j, bar in enumerate(bars):
percentage = '{:.2f}%'.format(100 * bar.get_height())
x_pos = bar.get_x() + bar.get_width() / 2
y_pos = bar.get_height()
ax.annotate(percentage, (x_pos, y_pos), rotation=90, xytext=(0, 4),
textcoords="offset points", ha="center", va="bottom", color='red')
# Set axis labels and title
ax.set_xlabel('Categories')
ax.set_ylabel('Percentage')
ax.set_title('Grouped Bar Charts')
# Set x-axis tick labels
ax.set_xticks(x + (len(group_names) - 1) * bar_width / 2)
ax.set_xticklabels(category_names)
# Set legend
ax.legend()
# Show the plot
plt.tight_layout()
plt.show()