Last active
February 8, 2017 17:02
-
-
Save ClodoaldoPinto/fa499bc8aaf205240aed4268aed13e12 to your computer and use it in GitHub Desktop.
Create a plot and insert data into Posgresql from given paths and points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import matplotlib.pyplot as plt | |
import psycopg2 | |
lines = [ # [((x,y),(x,y)...),] | |
((-10, 0),(10, 0),(8,3)), | |
((0, -10),(0, 10)), | |
((-10, -10),(-10, 10)), | |
((1, 1),(1, -1)), | |
((-7, -4),(-3, 4),(-5,6)), | |
((-9, -8),(4, -8)), | |
((-8, -9),(-8, 6)), | |
((2, 1),(4, -1)) | |
] | |
points = [ # [(x,y),...] | |
(3,0),(0,0),(0,5),(-8,-8),(2,-8),(5,0),(7,7),(-6,-2) | |
] | |
plt.axis([-11, 11, -11, 11]) | |
for l in lines: | |
l = zip(*l) | |
plt.plot(l[0], l[1]) | |
for p in points: | |
plt.plot(p[0], p[1], 'ro') | |
template = ','.join(['%s'] * len(lines)) | |
paths_values = [] | |
for l in lines: | |
paths_values.append(tuple((','.join(['{} {}'.format(p[0], p[1]) for p in l]),))) | |
insert_paths = ''' | |
truncate table path; | |
insert into path (path_text, path) | |
select st_astext(g), g | |
from (values {}) s(p), st_geomfromtext(format('linestring(%%s)', p)) g(g); | |
'''.format(template) | |
template = ','.join(['%s'] * len(points)) | |
points_values = [] | |
for p in points: | |
points_values.append(tuple(('{} {}'.format(p[0], p[1]),))) | |
insert_points = ''' | |
truncate table point; | |
insert into point (point_text, point) | |
select st_astext(g), g | |
from (values {}) s(p), st_geomfromtext(format('point(%%s)', p)) g(g); | |
'''.format(template) | |
conn = psycopg2.connect(database='cpn') | |
cursor = conn.cursor() | |
#print (cursor.mogrify(insert_paths, paths_values).decode('utf8')) | |
#print (cursor.mogrify(insert_points, points_values).decode('utf8')) | |
cursor.execute(insert_paths, paths_values) | |
cursor.execute(insert_points, points_values) | |
conn.commit() | |
conn.close() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment