Python pandas pivot matplotlib

时间:2017-03-21 22:46:22

标签: python pandas matplotlib graph pivot

我创建了以下python pandas数据透视表。

df_pv = pd.pivot_table(df,index=["Fiscal_Week"],columns=["Year"],values=["Category","Sales","Traffic"],
               aggfunc={"Category":len,"Sales":np.sum,"Traffic":np.sum},fill_value=0)

               Category             Sales                 Traffic       
Year    |2014 2015  2016 |  2014    2015    2016 |  2014    2015    2016
Fiscal_Week                                 
FW01      4    3    4       35678   654654  47547   567     231      765
FW02      2    6    7       6565    4686    34554   297     464      564
FW03      4    4    5       5867    56856   34346   287     45       324
FW04      2    5    3       8568    45745   3564    546     765      978
FW05      2    5    5       5685    3464    4754    325     235      654
FW06      4    3    2       56765   35663   3643    456     935      936
FW07      1    6    2       8686    2454    2463    324     728      598
FW08      6    2    3       34634   34543   4754    198     436      234

我想创建以下两个图:

Scatterplot:按销售量划分的广告系列数量,每年都有自己的颜色。

enter image description here

第二张图应为“财政周刊交通”。

enter image description here

我试过这个不成功的

df_pv.plot(x="Fiscal_Week", y="Sales")

KeyError: 'Fiscal_Week'

是否有更好的方法 - 例如不转动,但在图表中指定聚合?

1 个答案:

答案 0 :(得分:1)

您尝试将索引用作普通列。这是不可能的。

克服这个问题的方法:

  1. 重置索引reset_index()
  2. 明确使用索引.plot(x=df_pv.index, y="Sales")
  3. 隐含使用索引.plot(y="Sales", use_index=True)