Вставка строки кода plt.gca().lines[-1].get_xydata()
(прямо под линией, где вы создаете график: plt.plot(distances, alts, color='blue')
) позволит вам извлечь координаты xy для всех точек каждой линии, которую вы строите.
Iзатем создал пустой список line_coords
, чтобы сохранить координаты xy для каждой из четырех строк, а затем итерацию по каждому из этих четырех наборов координат с помощью алгоритма RDP:
rdp_res = []
for line in line_coords:
rdp_res.append(rdp(line))
Список rdp_res
содержит выходные данные алгоритма RDP для каждой из четырех строк:
[array([[4.92025194e+00, 3.80000000e+01],
[5.24522347e+01, 3.80000000e+01],
[8.59726863e+01, 3.77000000e+01],
...,
[3.07740662e+04, 3.60000000e+01],
[3.08035662e+04, 3.60000000e+01],
[3.08075068e+04, 3.59000000e+01]]),
array([[4.92025194e+00, 3.80000000e+01],
[5.24522347e+01, 3.80000000e+01],
[8.59726863e+01, 3.77000000e+01],
...,
[2.81487733e+04, 5.20000000e+01],
[2.81536662e+04, 5.18000000e+01],
[2.82000946e+04, 5.18000000e+01]]),
array([[4.92025194e+00, 3.80000000e+01],
[5.24522347e+01, 3.80000000e+01],
[8.59726863e+01, 3.77000000e+01],
...,
[2.37758154e+04, 1.26000000e+01],
[2.37973123e+04, 1.30000000e+01],
[2.38301772e+04, 1.38000000e+01]]),
array([[4.92025194e+00, 3.80000000e+01],
[5.24522347e+01, 3.80000000e+01],
[8.59726863e+01, 3.77000000e+01],
...,
[2.59717233e+04, 1.83600000e+02],
[2.60321544e+04, 1.83400000e+02],
[2.60884831e+04, 1.83400000e+02]])]
Мы можем сравнить количество координат в каждой строке:
line_coords[0].shape, line_coords[1].shape, line_coords[2].shape, line_coords[3].shape
((1167, 2), (2133, 2), (2869, 2), (3597, 2))
С количеством координат, оставшихся послезапуск RDP в каждой строке:
rdp_res[0].shape, rdp_res[1].shape, rdp_res[2].shape, rdp_res[3].shape
((1080, 2), (1947, 2), (2643, 2), (3360, 2))
Ниже я вставил ваш исходный код со всеми моими модификациями, включенными:
"""
File for importing route data from a json file
"""
import json
import os
import matplotlib.pyplot as plt
from rdp import rdp
import numpy as np
def get_data(file_name):
"""
method to retrieve JSON data from "file"
:param file_name: string representing file in which JSON data is stored
:return data: Pyhonic data created from JSON file information
"""
with open(os.path.join(os.sys.path[0], file_name), "r") as data_file:
data = json.load(data_file) # load data from JSON file
return data
if __name__== "__main__":
file_name = 'json_data.json'
routes = get_data(file_name)
print("Total Time")
print(routes[0]["totalTime"])
print("Total Distance")
print(routes[0]["totalDistance"])
routesPos = 0
edgePos = 0
edgeDistance = 0
alts = []
distances = []
line_coords = []
while routesPos < len(routes):
while edgePos < len(routes[routesPos]["edges"]):
edgeDistance = edgeDistance + routes[routesPos]["edges"][edgePos]["edgeDistance"]
distances.append(edgeDistance)
alts.append(routes[routesPos]["edges"][edgePos]["endLocation"]["alt"])
edgePos += 1
plt.plot(distances, alts, color='blue')
coords = plt.gca().lines[-1].get_xydata() # Get coords for most recently plotted line
line_coords.append(coords)
edgeDistance = 0
routesPos += 1
edgePos = 0
rdp_res = []
for line in line_coords:
rdp_res.append(rdp(line))