18

I've had similar problems where I want to visualize shapefiles quickly, and I've always found the Matplotlib way quite a lengthy way to accomplish such a small task. Instead I developed the "Python Geographic Visualizer" module, or GeoVis for short. Update: v0.2.0 is now out with lots of new functionality. With it visualizing shapefiles couldn't be easier: ...


17

For future references, here is the solution I have came to after following the advices above. import shapefile as shp # Requires the pyshp package import matplotlib.pyplot as plt sf = shp.Reader("test.shp") plt.figure() for shape in sf.shapeRecords(): x = [i[0] for i in shape.shape.points[:]] y = [i[1] for i in shape.shape.points[:]] plt.plot(...


15

The column= keyword can be used if you have values in a column which need to be mapped to a color (with a certain color map). But if you already have actual color names that you want to use directly, you can use the color keyword. You can pass a list/array of colors (with the same number of values as the number of rows) to this color keyword. For example ...


14

I came across a number of tutorials dealing with this topic that I wanted to share: So You’d Like To Make a Map Using Python - Stephan Hügel How to Make a US County Thematic Map Using Free Tools - Nathan Yau A Thematic Map in Python - Daniel Lewis Creating Map Visualizations in <10 lines of Python - Rob Story You might also consider using R: How to ...


13

Shapely Polygon object has attribute exterior. Shapely MultiPolygon object has Polygon object sequence. You should iterate over those polygons. You can do that using attribute geoms of MultiPolygon. Use this way: import shapely.geometry as sg import shapely.ops as so import matplotlib.pyplot as plt r1 = sg.Polygon([(0,0),(0,1),(1,1),(1,0),(0,0)]) r2 = sg....


12

I added that recipe to the rasterio documentation. Since it was such a simple shape, in this case I just unzipped the coords in the single record contained by the shapefile. That is, x, y = zip(*features[0]['coordinates'][0]), and then just plot. More generally, I use PolygonPatch from descartes, and matplotlib.collections. import fiona import rasterio ...


12

In geopandas >= 0.3 (released September 2017), the plotting of points is based on the scatter plot method of matplotlib under the hood, and this accepts a variable markersize. So now you can actually pass a column to markersize, what the OP did in the original question: import geopandas cities = geopandas.read_file(geopandas.datasets.get_path('...


12

You could normalize the color by using the TwoSlopeNorm function in matplotlib. import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import TwoSlopeNorm import geopandas as gpd # generate data gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) gdf = gdf[gdf.continent == 'Africa'] gdf['random'] = np.random.gamma(2, 2, len(...


11

You need to use matplotlib paths and patches and there is a Python module dedicated to plot polygons from shapefiles using these functions Descartes. As Pyshp (shapefile) has the geo_interface (New geo_interface for PyShp) convention, you can use it. polys = shapefile.Reader("polygon") # first polygon poly = polys.iterShapes().next().__geo_interface__ ...


10

If I use your first example matplotlib - extracting data from contour lines import matplotlib.pyplot as plt x = [1,2,3,4] y = [1,2,3,4] m = [[15,14,13,12],[14,12,10,8],[13,10,7,4],[12,8,4,0]] cs = plt.contour(x,y,m) The result is: The number of elements (lines) is given by: len(cs.collection) 7 and the result you want is the area of one of the polygons (...


10

An alternative, shorter way of plotting using @Kadir Şahbaz's answer: new_shape = so.cascaded_union([r1, r2, r3]) # Plot each polygon shape directly for geom in new_shape.geoms: plt.plot(*geom.exterior.xy) # Set (current) axis to be equal before showing plot plt.gca().axis("equal") plt.show()


9

Issue with accepted answer: To complete the accepted answer, one should note that the method will fail if either of these is true: There is more than one polygon for a given level There are "holes" in the polygon (in this case, the accepted answer would work but would create an invalid Polygon which can be problematic down the line) Code: The following ...


9

There is a Python module for that: Descartes (look at Plot shapefile with matplotlib for example) from geopandas import GeoDataFrame test = GeoDataFrame.from_file('poly1.shp') test.set_index('id', inplace=True) test.sort() test['geometry'] testid 0 POLYGON ((1105874.411110075 -6125459.381061088... 1 POLYGON ((1106076.359169902 -6125875.557806003... 2 ...


8

You can set limits to the axis without chaining original GDF. import geopandas as gp import matplotlib.pyplot as plt from shapely.geometry import LineString, MultiPoint, Polygon thesmallpoints=gp.GeoDataFrame([[MultiPoint([(0, 0), (1, 1), (1,2), (2,2)])]],columns=['geometry']) thelargeline=gp.GeoDataFrame([[LineString([(0, 0), (1, 1), (1,2), (20,20)])]],...


7

Yes, some of the tools use matplotlib. For example (in my 10.1 install): Multi-Distance Spatial Cluster Analysis (Ripleys K Function) <ArcGIS install folder>\ArcToolbox\Scripts\KFunction.py Incremental Spatial Autocorrelation (Moran's I) <ArcGIS install folder>\ArcToolbox\Scripts\MoransI_Increment.py Ordinary Least Squares <ArcGIS ...


6

You have to use the cartopy shapereader and play a bit with records and geometries: import matplotlib.pyplot as plt import cartopy import cartopy.io.shapereader as shpreader import cartopy.crs as ccrs ax = plt.axes(projection=ccrs.PlateCarree()) #ax.add_feature(cartopy.feature.LAND) ax.add_feature(cartopy.feature.OCEAN) #ax.add_feature(cartopy.feature....


6

You can add edge or face color to the feature ax.add_feature(shape_feature, facecolor='blue')


6

This is not a problem of Matplotlib but your script and the module you use for reading shapefiles 1) You know that there are points in the geometries of the Polygon shapefile thus eliminate try... except 2) you load and read the shapefile twice for x and y (memory) for shape in shp.shapeRecords(): xy = [i for i in shape.shape.points[:]] x = [i[0] ...


6

If you want to represent the continents side by side, you have to create subplots on the same fig. To do so, you can iterate through your group of continents. Here is an example: import geopandas as gpd import matplotlib.pyplot as plt world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) continent = world.groupby('continent') plt.figure() # ...


6

I think, It's most probably about Python GUI (especially Tkinter). Matplotlib uses Tkinter by default. I couldn't figure it out why, but If I change GUI package for matplotlib to PyQt4, no more crashing with one exception. First, I tried wxPython, but I encountered errors. Then I installed PyQt4 (cp27m‑win32) and after some editings on script like below, ...


5

Matplotlib Basemap has the ability to transform between coordinate systems. Have a look here. That page says: In order to plot data on a map, the coordinates of the data must be given in map projection coordinates. Calling a Basemap class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y map projection coordinates (in meters)....


5

I solved this problem. I was reading the raster file row-wise from top to bottom, and plotting it row-wise from bottom to top. Since, I can't do anything with plotting I flipped the array, and it worked. Below is the modification which I made, ds = gdal.Open('Path\\To\\Raster.tif') data = ds.ReadAsArray() data = np.flipud(data)


5

After the simple and understandable answer, I came up myself with a straightforward way to plot a whole shp with matplotlib. I feel geopandas should just update their plotting function because this one is simple but so much faster including the full flexibility of matplotlib - adding legend, title, etc. from descartes import PolygonPatch import geopandas as ...


5

Just to start, you could plot only a subset of the data. Maybe downsample by a factor of 4. Of course, you will need to think about resample method which would probably be bilinear in this case. What about something like the answer from this question here: https://stackoverflow.com/questions/8090229/resize-with-averaging-or-rebin-a-numpy-2d-array def ...


5

This is a working solution with laspy: import numpy as np import laspy from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # reading las file and copy points input_las = laspy.file.File("test.las", mode="r") point_records = input_las.points.copy() # getting scaling and offset parameters las_scaleX = input_las.header....


5

It looks like cartopy package a downsampled version of the Natural Earth 'shaded relief and water' image as the stock image. You could try the original version (available here) and use ax.imshow to load it (following the source for ax.stock_img quite closely). import os import cartopy.crs as ccrs import matplotlib.pyplot as plt from matplotlib.image ...


5

Look at Plot shapefile with islands with matplotlib for example. As with polygons you can use matplotlib paths and patches and there is a Python module dedicated to plot polygons from shapefiles using these functions Descartes. new_shape= so.unary_union([r1, r2, r3]) from descartes import PolygonPatch import matplotlib.pyplot as plt BLUE = '#6699cc' GRAY ...


5

The reason is that exterior and interiors have a canonical form which assumes counter-clockwise coordinates for exterior and clockwise for interiors. You have to normalize your result to see it correctly. Shapely does not have normalize function yet (which is available in PyGEOS) but doing the buffer(0) does the trick. fig, ax = plt.subplots() patch = ...


5

Look at What is meaning of scale on x and y axis of image using matplotlib A point vector shapefile (cartesian projection): import geopandas as gpd df = gpd.read_file("points.shp") df['x'] = df.geometry.x df['y'] = df.geometry.y df.head(2) id geometry x y 0 1 POINT (203734.167 89573.589) ...


Only top voted, non community-wiki answers of a minimum length are eligible