【问题标题】:Why do I get a 'None' in the title of the legend when plotting a pivot_table?为什么在绘制数据透视表时,图例的标题中会显示“无”?
【发布时间】:2020-05-01 15:11:28
【问题描述】:

我有一个数据框,然后我调用pivot_table 方法,然后绘制结果。

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'Date': ['2020-04-10', '2020-04-11', '2020-04-12', '2020-04-13','2020-04-10', '2020-04-11', '2020-04-12', '2020-04-13'],
'Station': ['Hogwarts', 'Hogwarts', 'Hogwarts', 'Hogwarts','Hogwarts', 'Hogwarts', 'Hogwarts', 'Hogwarts'],
'Direction': ['Southbound', 'Southbound', 'Southbound', 'Southbound','Northbound','Northbound','Northbound','Northbound'],
'Daily trains': [1,1,2,3,0,0,2,1]})

df['Date'] = pd.to_datetime(df['Date'],format="%Y-%m-%d")

df1 = df.pivot_table(index='Date', columns=['Station','Direction'],values=['Daily trains'])
fig, ax = plt.subplots(1)

df1.plot(ax=ax)
ax.figure.savefig('so.png',bbox_inches='tight')

结果如下:

为什么我的图例标题中会出现'None'

【问题讨论】:

    标签: pandas matplotlib pivot-table


    【解决方案1】:

    它标记列名。

    df1.columns.names
    #FrozenList([None, 'Station', 'Direction'])
    

    您提供了list 的值,但您只有一个值,因此它会在您的列 MultiIndex 中创建不必要的级别。删除[]

    ...

    df1 = df.pivot_table(index='Date', columns=['Station','Direction'], values='Daily trains')
    
    fig, ax = plt.subplots(1)
    df1.plot(ax=ax)
    


    如果您需要旋转多个列(即values = ['Daily Trains', 'Daily Accidents']),并且想要绘制所有列,那么您仍然会使用None 来获取该级别的名称。您可以在绘图之前将其重命名。

    df1.columns = df1.columns.rename('Category', level=0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 2011-02-21
      相关资源
      最近更新 更多