如何在Matplotlib中使用datetime将X轴仅标注为小时:分钟格式?
解决Matplotlib X轴时间显示为小时:分钟格式的问题
要让X轴显示小时:分钟格式,你需要手动指定Matplotlib的日期格式化器,替换默认的自动格式。具体操作如下:
- 导入
matplotlib.dates.DateFormatter模块 - 创建格式为
%H:%M的格式化器 - 将该格式化器绑定到X轴上
修改后的完整代码:
import datetime import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter x_axis_time = [datetime.datetime(2024, 1, 24, h, 0) for h in range(1,24)] y_axis_values = [n*50 for n in range(0,23)] plt.plot(x_axis_time, y_axis_values) # 设置X轴时间格式为小时:分钟 date_formatter = DateFormatter("%H:%M") plt.gca().xaxis.set_major_formatter(date_formatter) plt.gcf().autofmt_xdate() plt.show()
补充说明:
- 你注释掉的
[i.time() for i in x_axis_time]方法不生效,是因为Matplotlib对datetime.time类型的处理兼容性较差,直接使用datetime.datetime对象配合自定义格式化器是更可靠的方案。 - 格式字符串可按需调整:比如用
%I:%M %p可以显示12小时制并附带AM/PM标识,用%H:%M:%S则显示到秒级。
内容的提问来源于stack exchange,提问作者Ivan Castro
相关产品推荐
相关产品推荐

