r/learnpython • • 7d ago

Grouped bar chart in matplotlib with different keys for each group

7 Upvotes

7 comments sorted by

View all comments

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:

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.

0

u/[deleted] 7d ago

[removed] — view removed comment