文章目录
前言
调试寻路模块的时候,发现需要一个简单输出可视化路径信息的脚本,这样调试起来更方便。这种工具脚本 python 肯定是首选,因为它的库实在是很多。经过筛选呢,发现 matplotlib.pyplot 库可以满足需求。引入这个库,调用几个 api ,简单实现了,输入一组坐标,输出一个图形文件,带有横纵坐标轴和路点以及路点间的连线。形如:
环境准备
- 基础设施:python3;pip3
- pip install matplotlib 安装库
API
- pyplot.plot(list1_x, list1_y) 画线; list1_x 为 x 坐标数组,list1_y 为 y 坐标数组
- pyplot.savefig(filename) 重定向输出到文件;filename 为文件名
- pyplot.show() 执行画线并输出到文件
python 脚本
#!/usr/bin/python3
import matplotlib.pyplot as plt
import sys
# @coords [x1, y1, x2, y2, ...]
def drawRoad(coords, filename):
x_list = []
y_list = []
idx = 0
i = 0
lenth = len(coords)
while i < lenth - 1:
x_list.append(coords[i])
y_list.append(coords[i + 1])
idx = idx + 1
i = i + 2
pass
# print(x_list)
# print(y_list)
plt.plot(x_list, y_list)
plt.savefig(filename)
plt.show()
pass
# print(sys.argv[0])
# print(len(sys.argv))
coord_list = sys.argv[2:]
coord_list = [ float(x) for x in coord_list ]
filename = sys.argv[1]
drawRoad(coord_list, filename)
# plt.plot(["1536", "1536", "1604"], ["1593", "2002", "1590"])
# plt.savefig("draw.png")
# plt.show()
执行命令:
python3 draw.py filename x1 y1 x2 y2 ...
lua 脚本
想在 lua 脚本中调用画图怎么做呢,利用 lua 的 io 库 来调用 python 脚本即可。
-- @opt 系统命令
function os_excute(opt)
local t = io.popen(opt)
local a = t:read("*all")
return a
end
-- @画图接口
-- @pic_name 图片名字
-- @road 路径数据 {x1, y1, x2, y2, ...}
function draw_picture(pic_name, road)
local coords = table.concat(road, " ", 1, #road)
os_excute(string.format("python3 draw.py %s %s", pic_name, coords))
end
结语
pyplot.plot 还支持输出多条曲线,添加颜色设置等,需要的话可以查询 api 文档 进行扩展。