[英]Adjust timestamps on x-axis - Matplotlib
I am trying to create a line
plot
in order of time
. 我试图按time
顺序创建line
plot
。 For the df
below, the first value appears at 07:00:00
and finishes at 00:00:40
. 对于下面的df
,第一个值出现在07:00:00
并结束于00:00:40
。
But the timestamps
aren't assigned to the x-axis
and the row
after midnight
is plotted
first, instead of last. 但是, timestamps
未分配给x-axis
, midnight
之后的row
被首先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)
Your timedelta object is being converted to a numerical representation by matplotlib. matplotlib将您的timedelta对象转换为数字表示形式。 That's why you aren't getting a date on your x axis. 这就是为什么您没有在x轴上获得日期的原因。 And the plot is going in order. 而且剧情按顺序进行。 It's just that '00:40:00'
is less than all the other times so it's being plotted as the left most point. 只是'00:40:00'
小于所有其他时间,因此被绘制为最左边的点。
What you can do instead is use a datetime format to include days, which will indicate that 00:40:00
should come last since it'll fall on the next day. 相反,您可以使用日期时间格式来包含日期,这将指示00:40:00
应该倒数第二天,因为它将在第二天出现。 You can also use pandas plotting method for easier formatting: 您也可以使用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')
Update 更新资料
To set the tick/tick lables at your time points is a bit tricky. 要在您的时间点设置刻度线/刻度线,有些棘手。 This post will give you an idea of how the positioning works. 这篇文章将使您了解定位的工作原理。 Basically, you'll need to use something like matplotlib.dates.date2num
to get the numerical representation of datetime: 基本上,您需要使用类似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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.