0

I am trying to add data labels in bar chart and format y-axis.

I am working on e-commerce data. i have created bar chart - total sales by month. I have Data like - OrderDate and Total paid (amount for each order) column. I have grouped OrderDate by month and total sales. when I try to use

plt.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) 
  • to format y-axis by thousand its not working.

Also when i tried to add data labels using plt.patches its not working. it says no attribute get_yaxis and patches.

temp = df.loc[:,('OrderDate','total_paid')]
temp.OrderDate = df.OrderDate.dt.to_period('M')
temp = temp.groupby(['OrderDate'])['total_paid'].sum()
temp = temp.reset_index(drop = False)

plt.figure(figsize=(15,5))
plt.bar(np.arange(len(temp['OrderDate'])), temp['total_paid'], align='center', alpha=0.5)
plt.xticks(np.arange(len(temp['OrderDate'])), temp['OrderDate'])
plt.ylabel('Total Sales',fontsize=14)
plt.xlabel('Year-Month',fontsize=14)
plt.title('Total Sales by Month',fontsize=15)
#plt.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

I want to have y_axis in thousand and labels in each bar

amanb
  • 5,276
  • 3
  • 19
  • 38
  • Can you show your code for the bar labels? You should assign plt.bar() to a variable, like `ax = plt.bar(...)` and then look at the answers (maybe the second one) here: https://stackoverflow.com/questions/28931224/adding-value-labels-on-a-matplotlib-bar-chart – getup8 May 14 '19 at 06:09
  • Also, do the same for your yaxis. Try `ax.yaxis()` not `plt.yaxis()` (after creating `ax` as mentioned above) – getup8 May 14 '19 at 06:11
  • When i add "rects = ax.patches", i am getting below error --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () 15 #plt.set_xticklabels(temp['total_paid']) 16 ---> 17 rects = ax.patches 18 19 plt.tight_layout() AttributeError: 'Text' object has no attribute 'patches' – Dhusanth May 14 '19 at 08:16
  • Can you edit your question to show your actual code now where you set `ax` and reference `ax.patches`? – getup8 May 14 '19 at 22:27

0 Answers0