Skip to Content

Classe

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. """
  4. Plot_shapely.py
  5. Martin Laloux 2010
  6. """
  7. import pylab
  8. from shapely.wkt import loads
  9. from descartes.patch import PolygonPatch
  10. class Plot_shapely(object):
  11. """dessin de géométries Shapely avec matplotlib - pylab"""
  12.  
  13. def __init__(self,obj,ax, coul=None, alph=1):
  14. """
  15. Paramètres
  16. ----------------------------------------------------------------
  17. ax de pylab, obj = objet géometrique, coul = couleur matplotlib, alph = transparence
  18.  
  19. Exemple
  20. --------------------------------------------------------------------
  21. >>> from shapely.wkt import loads
  22. >>> ax = pylab.gca()
  23. >>> ligne = loads('LINESTRING (3 1, 4 4, 5 5, 5 6)')
  24. >>> a = Plot_shapely(ligne,ax,'r', 0.5)
  25. >>> a.plot
  26. ou directement
  27. >>> Plot_shapely(ligne,ax,'#FFEC00'').plot
  28. >>> pylab.show()
  29. """
  30. self.obj = obj
  31. self.type = obj.geom_type
  32. self.ax = ax
  33. self.coul= coul
  34. self.alph=alph
  35.  
  36. def plot_coords(self):
  37. """points"""
  38. x, y = self.obj.xy
  39. self.ax.plot(x, y, 'o', color=self.coul)
  40.  
  41. def plot_ligne(self):
  42. """lignes"""
  43. x, y = self.obj.xy
  44. self.ax.plot(x, y, color=self.coul, alpha=self.alph, linewidth=3)
  45.  
  46. def plot_polygone(self):
  47. """polygones"""
  48. patch = PolygonPatch(self.obj, facecolor=self.coul,edgecolor=self.coul, alpha=self.alph)
  49. self.ax.add_patch(patch)
  50.  
  51. def plot_multi(self):
  52. """multipoints, multilignes,multipolygones + GeometryCollection"""
  53. for elem in self.obj:
  54. Plot_shapely(elem, self.ax, self.coul,self.alph).plot
  55.  
  56.  
  57. @property
  58. def plot(self):
  59. """dessine en fonction du type géometrique"""
  60. if self.type == 'Point':
  61. self.plot_coords()
  62. elif self.type == 'Polygon':
  63. self.plot_polygone()
  64. elif self.type == 'LineString':
  65. self.plot_ligne()
  66. elif "Multi" in self.type:
  67. """ex. MultiPolygon"""
  68. self.plot_multi()
  69. elif self.type == 'GeometryCollection':
  70. self.plot_multi()
  71. elif self.type == 'LinearRing':
  72. self.plot_line()
  73. else:
  74. raise ValueError("inconnu au bataillon: %s" % self.type)
  75.  
  76. if __name__ == '__main__':
  77. import doctest
  78. doctest.testmod()