PostgreSQL 和 Python
我需要用Python来可视化来自“postgis”数据库(postgresql)的空间数据(20个多边形)。我知道怎么用Python连接postgresql数据库,但我不知道怎么把这些多边形可视化。这是我大学的一个项目。我们需要使用比如matplotlib这样的工具,创建一个Python应用程序来可视化来自postgresql数据库的形状文件(.shp)。
我开始写了这段代码,但不知道接下来该怎么做:
import psycopg2
conn = psycopg2.connect("dbname='***' user='***' host='***' password='***'")
print 'Succesfully connected'
cur = conn.cursor()
cur.execute("""SELECT astext(the_geom) from buildings;""")
listpoly = cur.fetchall()
conn.close()
5 个回答
1
你可以试试这个 patch_collection 示例。我把它的代码复制过来了,使用的是 matplotlib.pyplot,主要是关于多边形的部分:
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
patches = []
for x in xrange(2):
polygon = Polygon(np.random.rand(3, 2), True)
patches.append(polygon)
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
colors = 100*np.random.rand(len(patches))
p.set_array(np.array(colors))
ax.add_collection(p)
plt.colorbar(p)
plt.show()
输出的图片可以在 这里 找到:
我觉得这个文档 matplotlib.patches.Polygon 也值得一看。希望这些对你有帮助。
2
Python有很多绘图工具包,当然它们都支持绘制多边形,因为这是绘图中最基本的功能之一;-) 我认为最受欢迎的工具包是 matplotlib。
3
我在需要创建光栅(位图)图形时,使用Python图像库的体验非常好。这个库的界面很简单,能够很方便地在一张图片上叠加其他图形。不过,PIL更新得不太频繁,可能是因为它本身就很好用。下面是如何绘制一个简单的多边形(这个方法是从Nadia Alrami对PIL的优秀介绍中摘录的):
im = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) # Create a blank image
draw = ImageDraw.Draw(im)
lines = [(50, 0), (0, 40), (20, 100), (80, 100), (100, 40)]
draw.polygon(lines, fill="black")
对于更复杂的图像,我通常会使用svgfig这个Python包来渲染SVG格式的图像。因为是SVG格式,所以它们在浏览器中缩放和分享都很方便。不过,我觉得svgfig没有一个很好的多边形绘制功能,所以你需要自己动手实现,像这样:
def polygon(points):
for x in xrange(len(points)-1):
line(points[x][0], points[x][1], points[x+1][0], points[x+1][1])
line(points[-1][0], points[-1][1], points[0][0], points[0][1])