如何将定位系统的(x,y)时序坐标存入Prometheus并用Grafana XY Chart展示
实现定位坐标存入Prometheus并在Grafana展示XY散点图
方案原理
Prometheus的指标模型是单数值+标签,无法直接存储(x,y)坐标对,但可以通过两个独立指标+共享关联标签的方式绕开限制:
- 定义两个Gauge指标(
location_x、location_y)分别存储x、y坐标 - 给两个指标添加相同的唯一标签(如
sample_id),确保同一组(x,y)对应同一个标签值 - Grafana的XY Chart通过共享标签关联两个指标的数值,生成历史散点图
实现代码(Python Exporter)
用prometheus-client库编写自定义Exporter,每秒生成并暴露定位坐标:
from prometheus_client import start_http_server, Gauge import time import random from uuid import uuid4 # 定义带sample_id标签的Gauge指标 location_x = Gauge('location_x', 'X coordinate of positioning data', ['sample_id']) location_y = Gauge('location_y', 'Y coordinate of positioning data', ['sample_id']) def get_position(): # 替换为你的定位系统坐标获取逻辑,这里用随机值模拟 x = random.uniform(0, 100) y = random.uniform(0, 100) return x, y if __name__ == '__main__': # 启动HTTP服务,端口9100 start_http_server(9100) print("Position exporter running on http://localhost:9100") while True: x_coord, y_coord = get_position() # 生成唯一ID关联当前坐标对 sample_id = str(uuid4()) # 更新指标值 location_x.labels(sample_id=sample_id).set(x_coord) location_y.labels(sample_id=sample_id).set(y_coord) time.sleep(1)
Grafana配置步骤
- 添加数据源:在Grafana中添加Prometheus数据源,地址填写Exporter的访问地址(如
http://localhost:9100) - 创建XY Chart面板:
- 新建面板,选择
XY Chart可视化类型 - 在
Queries标签页添加两个查询:- 第一个查询:输入
location_x,别名设为X - 第二个查询:输入
location_y,别名设为Y
- 第一个查询:输入
- 在
Panel options标签页找到Data matching,选择By labels,并指定匹配标签为sample_id
- 新建面板,选择
- 查看散点图:调整时间范围,即可看到指定时间段内的历史(x,y)散点分布
注意事项
- 如果定位系统每秒可能生成多组坐标,建议用UUID作为
sample_id避免冲突;若每秒仅一组,也可用时间戳(如str(int(time.time())))作为标签值 - Prometheus默认的存储保留时间可通过配置调整,确保能展示足够的历史数据
内容的提问来源于stack exchange,提问作者Jet Lee
相关产品推荐
相关产品推荐

