Python plot_date:如何在图形轴上格式化时间和日期

如何解决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')

生成下图: figure with times vs date,nicely formatted

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-