【问题标题】:How to display DateTimeIndex x_tick labels如何显示 DateTimeIndex x_tick 标签
【发布时间】:2019-05-16 20:12:29
【问题描述】:

我有一个带有 DateTimeIndex 的 Pandas 系列,我将其绘制为线图。我希望我的 x_ticks 和 x_tick 标签只是该系列的 DateTimeIndex。

使用下面的代码,我正在显示我想要的 x_ticks,但我还将“Jan 2019”和“Feb”都添加到 x_tick 标签中,以及在每端的值 30 和 10 x 轴(它们是第一个和最后一个 DateTimeIndex 的日期值)。

w_c = pd.date_range(start=pd.to_datetime('2018-12-30'), end=pd.to_datetime('2019-02-10'), freq='w')
sales = [111.94, 193.44, 143.46, 157.26, 124.8, 206.26, 127.22]
test = pd.Series(sales, index=w_c)

fig,ax = plt.subplots(figsize=(8,7))
ax = test.plot(fontsize=10, color='darkorange', lw=0.8, ylim=(0,250))
ax.xaxis.grid(True, which="both")

ax.xaxis.set_ticklabels(test.index.strftime('%d/%m/%Y'), rotation=25, minor=True)

display(fig)

谁能告诉我如何删除这些额外的标签?我希望 x_tick 标签仅是我的测试系列中的 DateTimeIndex。

在此处查看屏幕截图,红色圈出不需要的标签

【问题讨论】:

    标签: pandas plot series


    【解决方案1】:

    一个快速的解决方案是绘制

    w_c = pd.date_range(start=pd.to_datetime('2018-12-30'), end=pd.to_datetime('2019-02-10'), freq='w')
    sales = [111.94, 193.44, 143.46, 157.26, 124.8, 206.26, 127.22]
    test = pd.Series(sales, index=w_c)
    
    fig,ax = plt.subplots(figsize=(8,7))
    
    # plot on ranks of rows instead of index
    ax.plot(range(len(test)), test, color='darkorange', lw=0.8)
    ax.set_ylim(0,250)
    ax.xaxis.grid(True, which="both")
    
    # manually modify the label
    ax.set_xticklabels([''] + test.index.strftime('%d/%m/%Y').to_list(), rotation=25)
    

    输出:

    【讨论】:

    • 谢谢。我只需要将最后一行更改为:ax.set_xticklabels(list(test.index.strftime('%d/%m/%Y')), rotation=25) 即可。似乎需要做一件疯狂的事情!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2011-09-26
    • 2014-01-20
    相关资源
    最近更新 更多