如何解决Python plot_date:如何在图形轴上格式化时间和日期
我正在研究一个图形,它应该简单地在 y 轴上绘制时间,在 x 轴上绘制日期。 我的输入是一个日期字符串,我已经在 timedate 的帮助下将其转换为日期。
我也设法得到了这个数字,但很难格式化轴。我找到了为 matplotlib.dates 打勾标签的示例,但没有为我的 datetime 类型的对象打勾。目标是在 y 轴(0、3、6、9.....24)上每 3 小时进行一次滴答,在 x 轴上每全年和每月进行一次滴答。
输入是一个列表,其中包含“snapshot”类型的对象,在属性snapshot.date 中具有字符串类型的日期,包括日期和时间(例如'21.02.2021 08:47')。字符串被格式化为日期时间。当它们用 strftime 分隔到日期和时间时,它们不幸地被转换为字符串。所以我用 strptime 将它们转换回日期/时间。有没有更好的方法来保持日期格式并将时间和日期分开?
代码如下
fig,(ax1) = plt.subplots(1,1,figsize=(7.5,5)) # Create a figure and an axes.
datetime_object_list = [datetime.strptime(snapshot.date,'%d.%m.%Y %H:%M') for snapshot in snapshots if snapshot.stcd == stcd_ID]
date_string_list = [datetime.strftime(datetime_object,'%d %m %y') for datetime_object in datetime_object_list]
date_object_list = [datetime.strptime(date_string,'%d %m %y').date() for date_string in date_string_list]
time_string_list = [datetime.strftime(datetime_object,'%H:%M') for datetime_object in datetime_object_list]
time_object_list = [datetime.strptime(time_string,'%H:%M').time() for time_string in time_string_list]
# plot sensors
ax1.plot_date(date_object_list,time_object_list,xdate=True,ydate=True,marker='o',color='C1')
# define limits of axes
y_min = datetime.strptime('00:00','%H:%M').time()
y_max = datetime.strptime('23:59','%H:%M').time()
ax1.set_ylim(y_min,y_max)
到目前为止,输出如下所示: enter image description here
如果有人有想法,那就太好了! 非常感谢,BR 克劳斯
解决方法
我设法用 xticks 和 yticks 解决了这个问题,还准备了一个更好的示例代码,可以独立运行:
import matplotlib.pyplot as plt
from datetime import datetime
dt1 = datetime(2011,11,1,23,2)
dt2 = datetime(2011,10,2)
dt3 = datetime(2011,8,12,3,2)
dt4 = datetime(2011,14,2)
dt5 = datetime(2011,9,2,2)
dt6 = datetime(2010,5,13,2)
dt7 = datetime(2010,4,2)
dt8 = datetime(2010,2)
dt9 = datetime(2010,2)
dt_list = [dt1,dt2,dt3,dt4,dt5,dt6,dt7,dt8,dt9]
year_list = [dt.year for dt in dt_list]
year_set = list(set(year_list)) # liste statt set,damit unten index funktioniert!
fig,ax1 = plt.subplots()
# create scatter plots for each year with different color
for year in year_set:
dt_list_year = [dt for dt in dt_list if dt.year == year]
t__list = [dt.time() for dt in dt_list_year]
d__list = [datetime.strptime(str(dt.month) + ' ' + str(dt.day),'%m %d').date() for dt in dt_list_year] # month and day without year -> referece to year 1900 automatically
ax1.plot_date(d__list,t__list,xdate=True,ydate=True,color="C" + str(year_set.index(year)),label=str(year))
# formatting x
month = list(range(1,13))
x_ticks_ = [datetime.strptime(str(month_i),'%m').date() for month_i in month]
x_labels = [x_ticksi.strftime('%b') for x_ticksi in x_ticks_] # '%b' -> Jan,Feb,Mar etc.
plt.xticks(x_ticks_,x_labels)
# formatting y
hours = list(range(0,24,2))
y_ticks_ = [datetime.strptime(str(hours_i),'%H').time() for hours_i in hours]
plt.yticks(y_ticks_)
ax1.set_xlabel('month')
ax1.legend(loc='best')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。