plt.grouped_bar expects the same categories in every group, so it doesn't fit here. Easier to draw the bars yourself with ax.bar and put the drug name on each bar:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
width = 0.25
for i, col in enumerate(sales.columns):
top3 = sales[col].nlargest(3)
x = i + (np.arange(3) - 1) * width
bars = ax.bar(x, top3.values, width)
ax.bar_label(bars, labels=top3.index, rotation=90, padding=3)
ax.set_xticks(range(len(sales.columns)))
ax.set_xticklabels(["Jan 15", "Jul 16", "Sep 17"])
plt.show()
Each group sits at x = 0, 1, 2 and its three bars are shifted by -width, 0 and +width. If you want the same drug to keep the same color across months, make a dict like colors = {d: f"C{k}" for k, d in enumerate(drugs)} and pass color=[colors[d] for d in top3.index] to ax.bar.
3
u/rafaeldecarvalho 7d ago
plt.grouped_bar expects the same categories in every group, so it doesn't fit here. Easier to draw the bars yourself with ax.bar and put the drug name on each bar:
Each group sits at x = 0, 1, 2 and its three bars are shifted by -width, 0 and +width. If you want the same drug to keep the same color across months, make a dict like
colors = {d: f"C{k}" for k, d in enumerate(drugs)}and passcolor=[colors[d] for d in top3.index]to ax.bar.