PyPlot子图X轴添加毫秒精度时间戳并设置标签旋转
解决Matplotlib时间轴标签多余零及刻度优化问题
核心问题:去除时间戳标签末尾的多余零
Matplotlib的mdates.DateFormatter使用%f时会强制输出6位微秒,导致毫秒级数据显示为13:25:36.347000这类带多余零的格式。解决方法是使用自定义格式化函数,通过FuncFormatter灵活控制输出精度。
完整解决方案代码
import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.ticker import FuncFormatter # 原始数据 ts = [' 13:25:36.347', ' 13:25:36.350', ' 13:25:36.353', ' 13:25:36.357', ' 13:25:36.366'] ts = pd.to_datetime(ts, format=" %H:%M:%S.%f") y = pd.DataFrame([-0.005563,-0.000910,0.002366,0.002868,-0.000303], dtype=float) fig = plt.figure(figsize=(10,8)) ax = fig.add_subplot(1, 1, 1) ax.plot(ts, y) # 设置刻度间隔:每0.1秒(100000微秒)一个刻度 ax.xaxis.set_major_locator(mdates.MicrosecondLocator(interval=100000)) # 自定义时间格式化函数:保留毫秒精度(三位小数) def format_ms(x, pos): dt = mdates.num2date(x) # 截取到毫秒位,去掉末尾的三位零 return dt.strftime('%H:%M:%S.%f')[:-3] # 自定义时间格式化函数:保留厘秒精度(两位小数) # def format_cs(x, pos): # dt = mdates.num2date(x) # return dt.strftime('%H:%M:%S.%f')[:-4] # 应用自定义格式化器 ax.xaxis.set_major_formatter(FuncFormatter(format_ms)) # 设置标签垂直旋转,避免重叠 ax.xaxis.set_tick_params(rotation=90) ax.legend(loc="best") plt.tight_layout() plt.show()
关键说明
自定义格式化函数:
mdates.num2date(x)将Matplotlib内部的日期数值转换为Pythondatetime对象- 通过字符串切片
[:-3]保留到毫秒位(去掉最后三位微秒零),[:-4]则保留到厘秒位 - 如果需要自动去除所有末尾零(不固定精度),可以改用以下函数:
def format_auto(x, pos): dt = mdates.num2date(x) s = dt.strftime('%H:%M:%S.%f') # 去掉末尾的零,直到遇到非零字符,若小数点后全零则去掉小数点 return s.rstrip('0').rstrip('.') if '.' in s else s
刻度优化:
- 使用
MicrosecondLocator(interval=100000)确保每0.1秒生成一个刻度,平衡密度与可读性 set_tick_params(rotation=90)实现标签垂直旋转,彻底解决大数量数据下的标签重叠问题
- 使用
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

