【问题标题】:how to remove redundant date time when x-axis is incontinuous pandas DatetimeIndex当x轴不连续时如何删除多余的日期时间 pandas DatetimeIndex
【发布时间】:2017-11-25 04:55:23
【问题描述】:

我想绘制一个索引为无数 DatatimeIndex 的熊猫系列。我的代码如下:

import matplotlib.dates as mdates
index = pd.DatetimeIndex(['2000-01-01 00:00:00', '2000-01-01 00:01:00',
           '2000-01-01 00:02:00', '2000-01-01 00:03:00',
           '2000-01-01 00:07:00',
           '2000-01-01 00:08:00'],
          dtype='datetime64[ns]')
df = pd.Series(range(6), index=index)
print(df)
plt.plot(df.index, df.values)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%M"))
plt.show()

输出为: 但结果并不是我真正想要的,因为 2000-01-01 00:04:00 也绘制在图像上。期望的结果是在 x 轴上 03:00 在 07:00 旁边,并且图像应该是一条直线。希望你的好主意。

【问题讨论】:

    标签: python pandas matplotlib series


    【解决方案1】:

    一种可能的解决方案是通过strftime 将索引转换为string 并使用Series.plot

    s = pd.Series(range(6), index=index)
    print(s)
    2000-01-01 00:00:00    0
    2000-01-01 00:01:00    1
    2000-01-01 00:02:00    2
    2000-01-01 00:03:00    3
    2000-01-01 00:07:00    4
    2000-01-01 00:08:00    5
    dtype: int32
    
    s.index = s.index.strftime('%M')
    s.plot()
    

    另一种解决方案是由arange绘制,然后添加xticks

    x = np.arange(len(s.index))
    plt.plot(x, s)
    plt.xticks(x, s.index.strftime('%M'))
    plt.show()
    

    【讨论】:

    • 在我的项目中,我使用LineCollection 绘制了一条多色线。你可以看看我之前的问题。 stackoverflow.com/questions/44642966/… LineCollection 要求坐标能够“浮动”。这种方法虽然很好,但是在我的项目中并不能使用。还是谢谢你。
    • @JZeng 我认为这个答案直接适用于您的问题。你试过用它吗?有什么问题?
    • 对不起,我的粗心,这个方法真的适用于我的项目。但是 xticks 太密集了。我想显示“年”而不是“分钟”,但我发现设置定位器和格式化程序没有帮助。你有什么好主意吗?非常感谢您的好意。
    • plt.xticks(x, s.index.strftime('%Y')) 不起作用?也许需要通过strftime.org 更改它。
    • 比如2012分钟太多了,如果我用plt.xticks(x, s.index.strftime(%Y)),x轴上2012太多了,每分钟一个2012,但是我只想要一个2012一年的数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 2015-02-25
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多