Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import numpy as np 

2 

3from matplotlib.contour import ContourSet 

4from matplotlib.tri.triangulation import Triangulation 

5 

6 

7class TriContourSet(ContourSet): 

8 """ 

9 Create and store a set of contour lines or filled regions for 

10 a triangular grid. 

11 

12 User-callable method: clabel 

13 

14 Useful attributes: 

15 ax: 

16 the axes object in which the contours are drawn 

17 collections: 

18 a silent_list of LineCollections or PolyCollections 

19 levels: 

20 contour levels 

21 layers: 

22 same as levels for line contours; half-way between 

23 levels for filled contours. See _process_colors method. 

24 """ 

25 def __init__(self, ax, *args, **kwargs): 

26 """ 

27 Draw triangular grid contour lines or filled regions, 

28 depending on whether keyword arg 'filled' is False 

29 (default) or True. 

30 

31 The first argument of the initializer must be an axes 

32 object. The remaining arguments and keyword arguments 

33 are described in the docstring of `tricontour`. 

34 """ 

35 ContourSet.__init__(self, ax, *args, **kwargs) 

36 

37 def _process_args(self, *args, **kwargs): 

38 """ 

39 Process args and kwargs. 

40 """ 

41 if isinstance(args[0], TriContourSet): 

42 C = args[0].cppContourGenerator 

43 if self.levels is None: 

44 self.levels = args[0].levels 

45 else: 

46 from matplotlib import _tri 

47 tri, z = self._contour_args(args, kwargs) 

48 C = _tri.TriContourGenerator(tri.get_cpp_triangulation(), z) 

49 self._mins = [tri.x.min(), tri.y.min()] 

50 self._maxs = [tri.x.max(), tri.y.max()] 

51 

52 self.cppContourGenerator = C 

53 return kwargs 

54 

55 def _get_allsegs_and_allkinds(self): 

56 """ 

57 Create and return allsegs and allkinds by calling underlying C code. 

58 """ 

59 allsegs = [] 

60 if self.filled: 

61 lowers, uppers = self._get_lowers_and_uppers() 

62 allkinds = [] 

63 for lower, upper in zip(lowers, uppers): 

64 segs, kinds = self.cppContourGenerator.create_filled_contour( 

65 lower, upper) 

66 allsegs.append([segs]) 

67 allkinds.append([kinds]) 

68 else: 

69 allkinds = None 

70 for level in self.levels: 

71 segs = self.cppContourGenerator.create_contour(level) 

72 allsegs.append(segs) 

73 return allsegs, allkinds 

74 

75 def _contour_args(self, args, kwargs): 

76 if self.filled: 

77 fn = 'contourf' 

78 else: 

79 fn = 'contour' 

80 tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, 

81 **kwargs) 

82 z = np.ma.asarray(args[0]) 

83 if z.shape != tri.x.shape: 

84 raise ValueError('z array must have same length as triangulation x' 

85 ' and y arrays') 

86 

87 # z values must be finite, only need to check points that are included 

88 # in the triangulation. 

89 z_check = z[np.unique(tri.get_masked_triangles())] 

90 if np.ma.is_masked(z_check): 

91 raise ValueError('z must not contain masked points within the ' 

92 'triangulation') 

93 if not np.isfinite(z_check).all(): 

94 raise ValueError('z array must not contain non-finite values ' 

95 'within the triangulation') 

96 

97 z = np.ma.masked_invalid(z, copy=False) 

98 self.zmax = float(z_check.max()) 

99 self.zmin = float(z_check.min()) 

100 if self.logscale and self.zmin <= 0: 

101 raise ValueError('Cannot %s log of negative values.' % fn) 

102 self._contour_level_args(z, args[1:]) 

103 return (tri, z) 

104 

105 

106def tricontour(ax, *args, **kwargs): 

107 """ 

108 Draw contours on an unstructured triangular grid. 

109 

110 `.tricontour` and `.tricontourf` draw contour lines and filled contours, 

111 respectively. Except as noted, function signatures and return values are 

112 the same for both versions. 

113 

114 The triangulation can be specified in one of two ways; either :: 

115 

116 tricontour(triangulation, ...) 

117 

118 where *triangulation* is a `matplotlib.tri.Triangulation` object, or :: 

119 

120 tricontour(x, y, ...) 

121 tricontour(x, y, triangles, ...) 

122 tricontour(x, y, triangles=triangles, ...) 

123 tricontour(x, y, mask=mask, ...) 

124 tricontour(x, y, triangles, mask=mask, ...) 

125 

126 in which case a `.Triangulation` object will be created. See that class' 

127 docstring for an explanation of these cases. 

128 

129 The remaining arguments may be:: 

130 

131 tricontour(..., Z) 

132 

133 where *Z* is the array of values to contour, one per point in the 

134 triangulation. The level values are chosen automatically. 

135 

136 :: 

137 

138 tricontour(..., Z, N) 

139 

140 contour up to *N+1* automatically chosen contour levels (*N* intervals). 

141 

142 :: 

143 

144 tricontour(..., Z, V) 

145 

146 draw contour lines at the values specified in sequence *V*, 

147 which must be in increasing order. 

148 

149 :: 

150 

151 tricontourf(..., Z, V) 

152 

153 fill the (len(*V*)-1) regions between the values in *V*, 

154 which must be in increasing order. 

155 

156 :: 

157 

158 tricontour(Z, **kwargs) 

159 

160 Use keyword args to control colors, linewidth, origin, cmap ... see 

161 below for more details. 

162 

163 `.tricontour(...)` returns a `~matplotlib.contour.TriContourSet` object. 

164 

165 Optional keyword arguments: 

166 

167 *colors*: [ *None* | string | (mpl_colors) ] 

168 If *None*, the colormap specified by cmap will be used. 

169 

170 If a string, like 'r' or 'red', all levels will be plotted in this 

171 color. 

172 

173 If a tuple of matplotlib color args (string, float, rgb, etc), 

174 different levels will be plotted in different colors in the order 

175 specified. 

176 

177 *alpha*: float 

178 The alpha blending value 

179 

180 *cmap*: [ *None* | Colormap ] 

181 A cm :class:`~matplotlib.colors.Colormap` instance or 

182 *None*. If *cmap* is *None* and *colors* is *None*, a 

183 default Colormap is used. 

184 

185 *norm*: [ *None* | Normalize ] 

186 A :class:`matplotlib.colors.Normalize` instance for 

187 scaling data values to colors. If *norm* is *None* and 

188 *colors* is *None*, the default linear scaling is used. 

189 

190 *levels* [level0, level1, ..., leveln] 

191 A list of floating point numbers indicating the level 

192 curves to draw, in increasing order; e.g., to draw just 

193 the zero contour pass ``levels=[0]`` 

194 

195 *origin*: [ *None* | 'upper' | 'lower' | 'image' ] 

196 If *None*, the first value of *Z* will correspond to the 

197 lower left corner, location (0, 0). If 'image', the rc 

198 value for ``image.origin`` will be used. 

199 

200 This keyword is not active if *X* and *Y* are specified in 

201 the call to contour. 

202 

203 *extent*: [ *None* | (x0, x1, y0, y1) ] 

204 

205 If *origin* is not *None*, then *extent* is interpreted as 

206 in :func:`matplotlib.pyplot.imshow`: it gives the outer 

207 pixel boundaries. In this case, the position of Z[0, 0] 

208 is the center of the pixel, not a corner. If *origin* is 

209 *None*, then (*x0*, *y0*) is the position of Z[0, 0], and 

210 (*x1*, *y1*) is the position of Z[-1,-1]. 

211 

212 This keyword is not active if *X* and *Y* are specified in 

213 the call to contour. 

214 

215 *locator*: [ *None* | ticker.Locator subclass ] 

216 If *locator* is None, the default 

217 :class:`~matplotlib.ticker.MaxNLocator` is used. The 

218 locator is used to determine the contour levels if they 

219 are not given explicitly via the *V* argument. 

220 

221 *extend*: [ 'neither' | 'both' | 'min' | 'max' ] 

222 Unless this is 'neither', contour levels are automatically 

223 added to one or both ends of the range so that all data 

224 are included. These added ranges are then mapped to the 

225 special colormap values which default to the ends of the 

226 colormap range, but can be set via 

227 :meth:`matplotlib.colors.Colormap.set_under` and 

228 :meth:`matplotlib.colors.Colormap.set_over` methods. 

229 

230 *xunits*, *yunits*: [ *None* | registered units ] 

231 Override axis units by specifying an instance of a 

232 :class:`matplotlib.units.ConversionInterface`. 

233 

234 tricontour-only keyword arguments: 

235 

236 *linewidths*: [ *None* | number | tuple of numbers ] 

237 If *linewidths* is *None*, defaults to rc:`lines.linewidth`. 

238 

239 If a number, all levels will be plotted with this linewidth. 

240 

241 If a tuple, different levels will be plotted with different 

242 linewidths in the order specified 

243 

244 *linestyles*: [ *None* | 'solid' | 'dashed' | 'dashdot' | 'dotted' ] 

245 If *linestyles* is *None*, the 'solid' is used. 

246 

247 *linestyles* can also be an iterable of the above strings 

248 specifying a set of linestyles to be used. If this 

249 iterable is shorter than the number of contour levels 

250 it will be repeated as necessary. 

251 

252 If contour is using a monochrome colormap and the contour 

253 level is less than 0, then the linestyle specified 

254 in :rc:`contour.negative_linestyle` will be used. 

255 

256 tricontourf-only keyword arguments: 

257 

258 *antialiased*: bool 

259 enable antialiasing 

260 

261 Note: `.tricontourf` fills intervals that are closed at the top; that is, 

262 for boundaries *z1* and *z2*, the filled region is:: 

263 

264 z1 < Z <= z2 

265 

266 except for the lowest interval, which is closed on both sides (i.e. it 

267 includes the lowest value). 

268 """ 

269 kwargs['filled'] = False 

270 return TriContourSet(ax, *args, **kwargs) 

271 

272 

273def tricontourf(ax, *args, **kwargs): 

274 kwargs['filled'] = True 

275 return TriContourSet(ax, *args, **kwargs) 

276 

277 

278tricontourf.__doc__ = tricontour.__doc__