You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib折线图中如何利用时间索引标记指定数据点?

解决Matplotlib中markevery无法使用时间索引标记数据点的问题

你遇到的错误是因为markevery参数不接受时间字符串或datetime对象作为输入——它需要的是数据点在数组中的整数位置索引,而不是时间标签值。Matplotlib绘图时按数据的顺序依次渲染,不会自动匹配时间标签来定位标记点。

解决步骤

  1. 确保要标记的时间格式和数据索引的格式完全一致(比如都转成datetime.time或带日期的datetime对象)
  2. 找到这些时间对应的整数下标
  3. 将整数下标列表传给markevery

具体代码示例

假设你的data是pandas DataFrame且索引为datetime类型,可按以下方式处理:

import matplotlib.pyplot as plt
import pandas as pd

# 处理要标记的时间,转成和数据索引匹配的格式
markers_on = ['13:15:00','13:30:00','13:45:00','14:00:00','14:15:00','14:30:00']
# 若数据索引仅包含时间部分,转成datetime.time对象
target_times = [pd.to_datetime(t).time() for t in markers_on]

# 匹配时间,提取对应的整数下标
mark_indices = [i for i, idx in enumerate(data.index) if idx.time() in target_times]

# 绘图,传入整数下标列表给markevery
ax1 = plt.subplot()
ax1.plot(data, '-gD', markevery=mark_indices)

ax1.set_xlabel("Time (HH:MM:SS)", fontsize=15)
ax1.set_ylabel("Temp", fontsize=15)
plt.show()

补充说明

  • 如果数据索引是带日期的完整datetime对象,需把markers_on也转成包含对应日期的datetime对象再匹配,比如pd.to_datetime(f'2024-01-01 {t}')
  • 也可以用numpy更高效地获取索引:
    import numpy as np
    target_datetimes = pd.to_datetime(markers_on)  # 需和数据索引格式一致
    mark_indices = np.where(data.index.isin(target_datetimes))[0]
    

内容的提问来源于stack exchange,提问作者Jim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:42:46