Matplotlib折线图中如何利用时间索引标记指定数据点?
解决Matplotlib中markevery无法使用时间索引标记数据点的问题
你遇到的错误是因为
markevery参数不接受时间字符串或datetime对象作为输入——它需要的是数据点在数组中的整数位置索引,而不是时间标签值。Matplotlib绘图时按数据的顺序依次渲染,不会自动匹配时间标签来定位标记点。
解决步骤
- 确保要标记的时间格式和数据索引的格式完全一致(比如都转成
datetime.time或带日期的datetime对象) - 找到这些时间对应的整数下标
- 将整数下标列表传给
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
相关产品推荐
相关产品推荐

