调整x轴上的时间戳 - Matplotlib

问题描述 投票:0回答:1

我试图按照line的顺序创建一个plot time。对于下面的df,第一个值出现在07:00:00并在00:00:40结束。

timestamps没有被分配到x-axisrow之后midnight首先是plotted,而不是最后。

import pandas as pd
import matplotlib.pyplot as plt

d = ({
    'Time' : ['7:00:00','10:30:00','12:40:00','16:25:00','18:30:00','22:40:00','00:40:00'],
    'Value' : [1,2,3,4,5,4,10],           
     })

df = pd.DataFrame(d)

df['Time'] = pd.to_timedelta(df['Time'])

plt.plot(df['Time'], df['Value'])

plt.show()

print(df)

enter image description here

python pandas matplotlib plot time
1个回答
2
投票

您的timedelta对象正在被matplotlib转换为数字表示。这就是为什么你没有在x轴上得到日期。情节正在顺序进行。只是'00:40:00'比其他所有时间都少,所以它被绘制为最左边的点。

你可以做的是使用日期时间格式来包括天数,这将表明00:40:00应该是最后一次,因为它将在第二天落下。您还可以使用pandas绘图方法来更轻松地进行格式化:

d = ({
    'Time' : ['2019/1/1 7:00:00','2019/1/1 10:30:00','2019/1/1 12:40:00',
              '2019/1/1 16:25:00','2019/1/1 18:30:00','2019/1/1 22:40:00',
              '2019/1/2 00:40:00'],
    'Value' : [1,2,3,4,5,4,10],           
})

df = pd.DataFrame(d)
df['Time'] = pd.to_datetime(df['Time'])

df.plot(x='Time', y='Value')

enter image description here


更新

在你的时间点设置刻度/刻度标签有点棘手。这个post将让您了解定位的工作原理。基本上,你需要使用像matplotlib.dates.date2num这样的东西来获得datetime的数字表示:

xticks = [matplotlib.dates.date2num(x) for x in df['Time']]
xticklabels = [x.strftime('%H:%M') for x in df['Time']]

ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.