【问题标题】:Add months to xaxis and legend on a matplotlib line plot在 matplotlib 线图上向 x 轴和图例添加月份
【发布时间】:2018-02-26 01:15:07
【问题描述】:

我正在尝试按月绘制堆积的年度折线图。 我有一个数据框 df_year 如下:

Day                    Number of Bicycle Hires            
2010-07-30                     6897

2010-07-31                     5564

2010-08-01                     4303

2010-08-02                     6642

2010-08-03                     7966

索引设置为从 2010 年 7 月到 2017 年 7 月的日期

我想为每年绘制一个折线图,xaxis 是从 1 月到 12 月的月份,并且只绘制每月的总和

我通过将数据框转换为如下所示的数据透视表来实现这一点:

pt = pd.pivot_table(df_year, index=df_year.index.month, columns=df_year.index.year, aggfunc='sum')

这将创建如下数据透视表,我可以绘制如下图所示:

  Number of Bicycle Hires    2010      2011       2012      2013       2014   
1                      NaN  403178.0   494325.0  565589.0   493870.0   
2                      NaN  398292.0   481826.0  516588.0   522940.0   
3                      NaN  556155.0   818209.0  504611.0   757864.0   
4                      NaN  673639.0   649473.0  658230.0   805571.0   
5                      NaN  722072.0   926952.0  749934.0   890709.0  

在 xaxis 上显示带有月份的年度数据

唯一的问题是月份显示为整数,我希望它们显示为 Jan、Feb ....Dec,每行代表一年。而且我无法为每一年添加一个图例。

我已经尝试了以下代码来实现这一点:

dims = (15,5)
fig, ax = plt.subplots(figsize=dims)
ax.plot(pt)

months = MonthLocator(range(1, 13), bymonthday=1, interval=1)
monthsFmt = DateFormatter("%b '%y")
ax.xaxis.set_major_locator(months) #adding this makes the month ints disapper
ax.xaxis.set_major_formatter(monthsFmt)
handles, labels = ax.get_legend_handles_labels() #legend is nowhere on the plot
ax.legend(handles, labels)

请任何人帮助我解决这个问题,我在这里做错了什么?

谢谢!

【问题讨论】:

    标签: python pandas matplotlib plot python-datetime


    【解决方案1】:

    您的图例句柄和标签中没有任何内容,此外,DateFormatter 没有返回正确的值,因为它们不是您翻译的 datetime 对象。

    您可以专门为日期设置索引,然后删除由pivot(“0”)创建的多索引列级别,然后在月份使用显式刻度标签,同时设置它们需要出现在您的x 轴。如下:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    import datetime
    
    # dummy data (Days)
    dates_d = pd.date_range('2010-01-01', '2017-12-31', freq='D')
    df_year = pd.DataFrame(np.random.randint(100, 200, (dates_d.shape[0], 1)), columns=['Data'])
    df_year.index = dates_d #set index
    
    pt = pd.pivot_table(df_year, index=df_year.index.month, columns=df_year.index.year, aggfunc='sum')
    pt.columns = pt.columns.droplevel() # remove the double header (0) as pivot creates a multiindex.
    
    ax = plt.figure().add_subplot(111)
    ax.plot(pt)
    
    ticklabels = [datetime.date(1900, item, 1).strftime('%b') for item in pt.index]
    ax.set_xticks(np.arange(1,13))
    ax.set_xticklabels(ticklabels) #add monthlabels to the xaxis
    
    ax.legend(pt.columns.tolist(), loc='center left', bbox_to_anchor=(1, .5)) #add the column names as legend.
    plt.tight_layout(rect=[0, 0, 0.85, 1])
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 2020-05-12
      • 1970-01-01
      • 2018-03-07
      • 2020-09-16
      • 2020-01-07
      • 2016-06-22
      • 1970-01-01
      • 2019-12-07
      相关资源
      最近更新 更多