【问题标题】:X tick labels for timeseries in multiindex pandas plot多索引熊猫图中时间序列的 X 刻度标签
【发布时间】:2021-09-03 20:20:51
【问题描述】:

我的原始数据框(df1)包含五年的月度数据。我按年和月进行分组,因为我想绘制五年期间(df_groupby)中“销售额”列的月度变化。生成的 groupby 生成一个多索引数据框,其中索引列和月份列都自动命名为“日期”。

df1:
            Dress     
Date                                                                  
2015-01-31  Suit
2015-02-28  Pant 
2015-03-31  Shirt

##df_groupby: to count the number of dresses sold in a given month per year
df_groupby=df1.groupby([(df1.index.year), (df1.index.month)]).count()

              Dress
Date    Date                    
2015    1   1   
        2   1   
        3   1   
        4   5   
        5   4   
         

现在,我想将五年内每月售出的连衣裙数量绘制为时间序列,这样月份应该显示为次要刻度标签,而年份应显示为主要刻度。我正在尝试这个;

g= df_groupby
ax = g.Station.plot()
ax.set_xticks(range(len(g)));
ax.set_xticklabels(["%s-%02d" % item for item in g.index.tolist()], rotation=45);

这给了我这样的情节(我不想要几周的日子/只是几个月和一年)-

但是,我想绘制一个带有 x 刻度标签的图,如下所示:

在这种情况下,格式化 x 刻度的好方法是什么?

【问题讨论】:

    标签: pandas dataframe time-series multi-index


    【解决方案1】:

    我猜有多种选择。其中之一是将FixedFormatter() 用作tick-formatter

    然后您可以将标签作为字符串传递,换行符\n 将导致多行刻度。为此,您必须先将刻度转换为字符串。

    import matplotlib.pyplot as plt
    from matplotlib import ticker
    
    
    def setup(ax, title):
        """Set up common parameters for the Axes in the example."""
        # only show the bottom spine
        ax.yaxis.set_major_locator(ticker.NullLocator())
    
        # define tick positions
        ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
        ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
    
        ax.xaxis.set_ticks_position('bottom')
        ax.tick_params(which='major', width=1.00, length=5)
        ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
        ax.set_xlim(0, 5)
        ax.set_ylim(0, 1)
        ax.text(0.0, 0.2, title, transform=ax.transAxes,
                fontsize=14, fontname='Monospace', color='tab:blue')
    
    fig1, axs1 = plt.subplots(2, 1, figsize=(8, 2))
    fig1.suptitle('Formatter Object Formatting')
    
    # Fixed formatter
    setup(axs1[1], title="FixedFormatter()")
    # FixedFormatter should only be used together with FixedLocator.
    # Otherwise, one cannot be sure where the labels will end up.
    positions = [0, 1, 2, 3, 4, 5]
    labels = ['A\na', 'B\nb', 'C\nc', 'D\nd', 'E\ne', 'F\nf']
    axs1[1].xaxis.set_major_locator(ticker.FixedLocator(positions))
    axs1[1].xaxis.set_major_formatter(ticker.FixedFormatter(labels))
    
    
    fig1.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2012-10-08
      • 2015-01-30
      • 2017-09-20
      • 2015-11-21
      • 2018-11-13
      • 2016-09-15
      • 2021-11-16
      • 2018-08-10
      • 2021-03-10
      相关资源
      最近更新 更多