I'm trying to plot a shapefile directly from PostGIS using Python. My shapefile is already stored in PostgreSQL. I know how to connect Python with PostgreSQL, but I just can't find anything that helps me plot my data into a map. I read somewhere that I should connect to PostgreSQL, query my shapefile table, select the geom attribute, store it into a geodataframe and then plot it.
Here's the code I'm using. Any ideas??
code example:
import psycopg2
import shapely
import osgeo.ogr
import shapely.wkt
import geopandas as gpd
import matplotlib.pyplot as plt
try:
conn = psycopg2.connect("dbname='strokes' user='postgres' host='localhost' password='****'")
except:
print "I am unable to connect to the database"
cur = conn.cursor()
cur.execute("CREATE INDEX bassin_index ON bassin USING GIST(geom)")
connection.commit()
cur.execute("SELECT st_astext(geom) AS wkt, fid_limite, codebassin FROM bassin")
rows = cur.fetchall()
rows_list=[]
for geom,fid_limite,codebassin in cursor:
data={'codebassin':codeb,'fidb':fidlim,'geom':shapely.wkt.loads(geom)}
rows_list.append(data)
gdf=gpd.GeoDataFrame(rows_list).set_index('codebassin')
gdf.head()
gdf.plot(column='rows_list', scheme='QUANTILES', k=5, colormap='gray')
plt.show()
conn.commit()
conn.close()
2 Answers 2
First, use method GeoDataFrame.from_postgis() from GeoPandas package to import geodata. Second, apply method GeoDataFrame.plot() to plot your data.
You might be interested to visit: "https://geohackweek.github.io/vector/06-geopandas-advanced/"
Try to use jupyter notebook
-
Welcome to GIS SE. More detailed answers are better... Can you add at least a brief outline from the link?Matt– Matt2017年05月23日 09:58:08 +00:00Commented May 23, 2017 at 9:58
Explore related questions
See similar questions with these tags.
postgres
user is extremely dangerous to the integrity of your database. Best practice is to create at least two logins, the first to own the data and the second only granted the permissions necessary to utilize the data (for a simple mapping app,SELECT
will suffice).