triplot.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import numpy as np
  2. from matplotlib.tri.triangulation import Triangulation
  3. def triplot(ax, *args, **kwargs):
  4. """
  5. Draw a unstructured triangular grid as lines and/or markers.
  6. The triangulation to plot can be specified in one of two ways; either::
  7. triplot(triangulation, ...)
  8. where triangulation is a `.Triangulation` object, or
  9. ::
  10. triplot(x, y, ...)
  11. triplot(x, y, triangles, ...)
  12. triplot(x, y, triangles=triangles, ...)
  13. triplot(x, y, mask=mask, ...)
  14. triplot(x, y, triangles, mask=mask, ...)
  15. in which case a Triangulation object will be created. See `.Triangulation`
  16. for a explanation of these possibilities.
  17. The remaining args and kwargs are the same as for `~.Axes.plot`.
  18. Returns
  19. -------
  20. lines : `~matplotlib.lines.Line2D`
  21. The drawn triangles edges.
  22. markers : `~matplotlib.lines.Line2D`
  23. The drawn marker nodes.
  24. """
  25. import matplotlib.axes
  26. tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
  27. x, y, edges = (tri.x, tri.y, tri.edges)
  28. # Decode plot format string, e.g., 'ro-'
  29. fmt = args[0] if args else ""
  30. linestyle, marker, color = matplotlib.axes._base._process_plot_format(fmt)
  31. # Insert plot format string into a copy of kwargs (kwargs values prevail).
  32. kw = kwargs.copy()
  33. for key, val in zip(('linestyle', 'marker', 'color'),
  34. (linestyle, marker, color)):
  35. if val is not None:
  36. kw[key] = kwargs.get(key, val)
  37. # Draw lines without markers.
  38. # Note 1: If we drew markers here, most markers would be drawn more than
  39. # once as they belong to several edges.
  40. # Note 2: We insert nan values in the flattened edges arrays rather than
  41. # plotting directly (triang.x[edges].T, triang.y[edges].T)
  42. # as it considerably speeds-up code execution.
  43. linestyle = kw['linestyle']
  44. kw_lines = {
  45. **kw,
  46. 'marker': 'None', # No marker to draw.
  47. 'zorder': kw.get('zorder', 1), # Path default zorder is used.
  48. }
  49. if linestyle not in [None, 'None', '', ' ']:
  50. tri_lines_x = np.insert(x[edges], 2, np.nan, axis=1)
  51. tri_lines_y = np.insert(y[edges], 2, np.nan, axis=1)
  52. tri_lines = ax.plot(tri_lines_x.ravel(), tri_lines_y.ravel(),
  53. **kw_lines)
  54. else:
  55. tri_lines = ax.plot([], [], **kw_lines)
  56. # Draw markers separately.
  57. marker = kw['marker']
  58. kw_markers = {
  59. **kw,
  60. 'linestyle': 'None', # No line to draw.
  61. }
  62. if marker not in [None, 'None', '', ' ']:
  63. tri_markers = ax.plot(x, y, **kw_markers)
  64. else:
  65. tri_markers = ax.plot([], [], **kw_markers)
  66. return tri_lines + tri_markers