【问题标题】:How to use two columns in x-axis如何在 x 轴上使用两列
【发布时间】:2020-12-03 01:06:20
【问题描述】:

我正在使用以下代码在 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"])

错误

谁能帮我更正我的代码以查看如下输出。

所需输出

【问题讨论】:

    标签: python python-3.x pandas matplotlib seaborn


    【解决方案1】:

    你的代码有几个问题:

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

    【讨论】:

    • 谢谢你,我已经修改了我的代码。但是如何在每个栏的顶部获取标签?
    • 不幸的是,似乎没有 seaborn 支持的解决方案,但您可以手动完成,例如见stackoverflow.com/questions/62002434/…。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      相关资源
      最近更新 更多