如何在X轴上使用两列

问题描述

我正在使用以下代码 x轴 Final_Sales 中获得 Segment Year y轴,但这会抛出一个错误

代码

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"])

错误

enter image description here

有人可以帮助我更正我的代码以查看以下输出吗?

必需的输出

enter image description here

解决方法

尝试添加另一对括号-result[["Segment","Year"]], 您尝试做的是检索名为-“细分”,“年份”, 但是实际上,您要尝试的是检索列的列表-[“ Segment”,“ Year”]。

,

您的代码有几个问题:

  • 使用多个列为数据框建立索引时,您希望将列列表传递给[](请参见docs),如下所示:
result[["Segment","Year"]]
sns.barplot(x = 'Segment',y = 'Final_Sales',hue = 'Year',data = result)