0

I have a bar chart but would like to put a label above each bar which corresponds the Net Sales of each age group to make the height of each bar more obvious to the reader, any ideas?

Code:

cd.loc[(cd.birth_year >= 1996) & (cd.birth_year <= 1998), "Age"] = "21 & Under"
cd.loc[(cd.birth_year >= 1983) & (cd.birth_year <= 1995), "Age"] = "22 to 34"
cd.loc[(cd.birth_year >= 1973) & (cd.birth_year <= 1982), "Age"] = "35 to 44"
cd.loc[(cd.birth_year >= 1963) & (cd.birth_year <= 1972), "Age"] = "45 to 54"
cd.loc[(cd.birth_year >= 1953) & (cd.birth_year <= 1962), "Age"] = "55 to 64"
cd.loc[(cd.birth_year >= 1900) & (cd.birth_year <= 1952), "Age"] = "65 & Over"
agedata = cd.groupby("Age").agg({"LTIME_NO_ORDERS": sum})

barplot = agedata.plot(kind="bar", colormap="Set3", legend=None)

# title and axis labels
plt.title("Net Sales of Age Groups", weight="bold", fontsize=20)
plt.ylabel("Net Sales (£)", fontsize=16)
plt.xlabel("Age", fontsize=16)
plt.xticks(rotation="horizontal")

rects = barplot.patches
labels = ["label1", "label2", "label3", "label4", "label5", "label6"]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    barplot.text(rect.get_x() + rect.get_width()/2, height+5, label, ha="center", va="bottom")

plt.show()

Current plot: enter image description here

Thanks for any help!

UPDATE: how do i make the labels automatically correspond to the age range sums as opposed to manually entering the label names?

Y. Luo
  • 5,622
  • 1
  • 18
  • 25
pow
  • 415
  • 3
  • 8
  • 18
  • Possible duplicate of [Adding value labels on a matplotlib bar chart](https://stackoverflow.com/questions/28931224/adding-value-labels-on-a-matplotlib-bar-chart) – Diziet Asahi Jul 01 '17 at 13:37
  • Thanks, have used the code. How do I make the labels automatically correspond to the age range sums as opposed to manually entering the label names? - post updated – pow Jul 01 '17 at 14:20
  • Try to input the variable height as label with: for rect in rects: height = rect.get_height() barplot.text(rect.get_x() + rect.get_width()/2, height+5, height, ha="center", va="bottom") – 2Obe Jul 01 '17 at 15:48

1 Answers1

0
rects = ax.patches
def autolabel(rects):
        for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
autolabel(rects)
David Buck
  • 3,752
  • 35
  • 31
  • 35