【问题标题】:How to plot a pandas multiindex dataFrame with all xticks如何绘制带有所有 xticks 的 pandas 多索引数据帧
【发布时间】:2014-02-12 09:59:10
【问题描述】:

我有一个这样的熊猫数据框:

                     content
date                        
2013-12-18 12:30:00        1
2013-12-19 10:50:00        1
2013-12-24 11:00:00        0
2014-01-02 11:30:00        1
2014-01-03 11:50:00        0
2013-12-17 16:40:00       10
2013-12-18 10:00:00        0
2013-12-11 10:00:00        0
2013-12-18 11:45:00        0
2013-12-11 14:40:00        4
2010-05-25 13:05:00        0
2013-11-18 14:10:00        0
2013-11-27 11:50:00        3
2013-11-13 10:40:00        0
2013-11-20 10:40:00        1
2008-11-04 14:49:00        1
2013-11-18 10:05:00        0
2013-08-27 11:00:00        0
2013-09-18 16:00:00        0
2013-09-27 11:40:00        0

日期是索引。 我使用以下方法将值减少到几个月:

dataFrame = dataFrame.groupby([lambda x: x.year, lambda x: x.month]).agg([sum])

哪个输出:

         content
             sum
2006 3        66
     4        65
     5        48
     6        87
     7        37
     8        54
     9        73
     10       74
     11       53
     12       45
2007 1        28
     2        40
     3        95
     4        63
     5        56
     6        66
     7        50
     8        49
     9        18
     10       28

现在,当我绘制这个数据框时,我希望 x 轴每个月/年显示为一个刻度。我尝试设置 xticks 但它似乎不起作用。这怎么可能实现?这是我当前使用 dataFrame.plot() 绘制的图:

【问题讨论】:

    标签: python matplotlib plot pandas


    【解决方案1】:

    您可以使用set_xtick()set_xticklabels()

    idx = pd.date_range("2013-01-01", periods=1000)
    val = np.random.rand(1000)
    s = pd.Series(val, idx)
    
    g = s.groupby([s.index.year, s.index.month]).mean()
    
    ax = g.plot()
    ax.set_xticks(range(len(g)));
    ax.set_xticklabels(["%s-%02d" % item for item in g.index.tolist()], rotation=90);
    

    输出:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-29
    • 2017-02-17
    • 2020-08-03
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2016-12-31
    相关资源
    最近更新 更多