Matplotlib绘图X轴时间缺失,求助显示完整日期时间刻度
问题:Matplotlib绘制时间-发电量折线图时X轴缺失时间部分,需显示完整日期和时间
我是Python初学者,尝试使用Matplotlib.pyplot绘制时间-发电量基础折线图。已将输入的date_time数据从字符串转换为datetime对象,但绘图后X轴的时间部分缺失,希望X轴刻度显示完整的日期和时间。
现有代码:
import matplotlib.dates as mdates fig , ax1 = plt.subplots() xfmt = mdates.DateFormatter('%d-%m-%y\n%H:%M:%S') ax1.xaxis.set_major_formatter(xfmt) ax1.plot(date_time, generation) fig.autofmt_xdate() plt.grid()
date_time列样本数据:
3 2024-03-01 00:04:05 14 2024-03-01 22:20:30 13 2024-03-02 03:56:23 16 2024-03-03 22:33:51 10 2024-03-04 14:46:24 31 2024-03-04 20:48:52 29 2024-03-05 01:31:23 4 2024-03-07 23:21:16
解决方案
你的代码已经定义了日期格式,但Matplotlib默认的刻度间隔可能过大,导致时间部分被省略。可以通过以下两种方式解决:
方式1:强制显示所有数据点的刻度
适合数据量不大的情况,确保每个样本的完整日期时间都能显示:
import matplotlib.pyplot as plt import matplotlib.dates as mdates fig, ax1 = plt.subplots(figsize=(10,6)) # 扩大画布,避免标签重叠 # 设置日期显示格式 xfmt = mdates.DateFormatter('%d-%m-%y\n%H:%M:%S') ax1.xaxis.set_major_formatter(xfmt) # 强制使用所有date_time数据作为X轴刻度 ax1.set_xticks(date_time) # 旋转标签角度,避免重叠 fig.autofmt_xdate(rotation=45) ax1.plot(date_time, generation) plt.grid() plt.show()
方式2:按固定间隔设置刻度
如果数据量较大,全部显示刻度会重叠,可以指定刻度间隔:
import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.dates import DayLocator, HourLocator fig, ax1 = plt.subplots(figsize=(10,6)) xfmt = mdates.DateFormatter('%d-%m-%y\n%H:%M:%S') ax1.xaxis.set_major_formatter(xfmt) # 示例:每12小时显示一个刻度 ax1.xaxis.set_major_locator(HourLocator(interval=12)) # 或者:每天显示一个刻度 # ax1.xaxis.set_major_locator(DayLocator()) fig.autofmt_xdate(rotation=45) ax1.plot(date_time, generation) plt.grid() plt.show()
关键说明:
figsize=(10,6):给X轴标签预留足够显示空间,防止重叠fig.autofmt_xdate(rotation=45):旋转标签角度,进一步优化显示效果- 两种方式都能保证X轴刻度显示完整的日期和时间,可根据数据量大小选择
内容的提问来源于stack exchange,提问作者Anu
相关产品推荐
相关产品推荐

