Find good place to draw a label (relatively flat part of the contour).
(self, linecontour, labelwidth)
| 265 | return fmt % lev |
| 266 | |
| 267 | def locate_label(self, linecontour, labelwidth): |
| 268 | """ |
| 269 | Find good place to draw a label (relatively flat part of the contour). |
| 270 | """ |
| 271 | ctr_size = len(linecontour) |
| 272 | n_blocks = int(np.ceil(ctr_size / labelwidth)) if labelwidth > 1 else 1 |
| 273 | block_size = ctr_size if n_blocks == 1 else int(labelwidth) |
| 274 | # Split contour into blocks of length ``block_size``, filling the last |
| 275 | # block by cycling the contour start (per `np.resize` semantics). (Due |
| 276 | # to cycling, the index returned is taken modulo ctr_size.) |
| 277 | xx = np.resize(linecontour[:, 0], (n_blocks, block_size)) |
| 278 | yy = np.resize(linecontour[:, 1], (n_blocks, block_size)) |
| 279 | yfirst = yy[:, :1] |
| 280 | ylast = yy[:, -1:] |
| 281 | xfirst = xx[:, :1] |
| 282 | xlast = xx[:, -1:] |
| 283 | s = (yfirst - yy) * (xlast - xfirst) - (xfirst - xx) * (ylast - yfirst) |
| 284 | l = np.hypot(xlast - xfirst, ylast - yfirst) |
| 285 | # Ignore warning that divide by zero throws, as this is a valid option |
| 286 | with np.errstate(divide='ignore', invalid='ignore'): |
| 287 | distances = (abs(s) / l).sum(axis=-1) |
| 288 | # Labels are drawn in the middle of the block (``hbsize``) where the |
| 289 | # contour is the closest (per ``distances``) to a straight line, but |
| 290 | # not `too_close()` to a preexisting label. |
| 291 | hbsize = block_size // 2 |
| 292 | adist = np.argsort(distances) |
| 293 | # If all candidates are `too_close()`, go back to the straightest part |
| 294 | # (``adist[0]``). |
| 295 | for idx in np.append(adist, adist[0]): |
| 296 | x, y = xx[idx, hbsize], yy[idx, hbsize] |
| 297 | if not self.too_close(x, y, labelwidth): |
| 298 | break |
| 299 | return x, y, (idx * block_size + hbsize) % ctr_size |
| 300 | |
| 301 | def _split_path_and_get_label_rotation(self, path, idx, screen_pos, lw, spacing=5): |
| 302 | """ |