1

I'm using the below code to get Segment and Year in x-axis and Final_Sales in y-axis but it is throwing me an error.

CODE

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
%matplotlib inline

order = pd.read_excel("Sample.xls", sheet_name = "Orders")
order["Year"] = pd.DatetimeIndex(order["Order Date"]).year
result = order.groupby(["Year", "Segment"]).agg(Final_Sales=("Sales", sum)).reset_index()

bar = plt.bar(x = result["Segment","Year"], height = result["Final_Sales"])

ERROR

enter image description here

Can someone help me to correct my code to see the output as below.

Required Output

enter image description here

Vikas
  • 189
  • 6

2 Answers2

1

Try to add another pair of brackets - result[["Segment","Year"]], What you tried to do is to retrieve column named - "Segment","Year", But actually what are you trying to do is to retrieve a list of columns - ["Segment","Year"].

activectd
  • 48
  • 4
0

There are several problems with your code:

  • When using several columns to index a dataframe you want to pass a list of columns to [] (see the docs) as follows :
result[["Segment","Year"]]
  • From the figure you provide it looks like you want to use year as hue. matplotlib.barplot doesn't have a hue argument, you would have to build it manually as described here. Instead you can use seaborn library that you are already importing anyway (see https://seaborn.pydata.org/generated/seaborn.barplot.html):
sns.barplot(x = 'Segment', y = 'Final_Sales', hue = 'Year', data = result)
perlusha
  • 153
  • 6
  • thanks for that, i've modified my code. But how to get labels at the top of every bar? – Vikas Aug 13 '20 at 09:39
  • Unfortunately, it looks like there is no seaborn-supported solution, but you can do it manually, e.g. see https://stackoverflow.com/questions/62002434/how-to-add-data-labels-to-seaborn-barplot. – perlusha Aug 13 '20 at 10:09