| 1 |
""" |
| 2 |
.. _distance_along_spline_example: |
| 3 |
|
| 4 |
Label based on Distance on Line |
| 5 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 6 |
|
| 7 |
Create a spline and generate labels along the spline based on distance along a |
| 8 |
spline. |
| 9 |
|
| 10 |
This is an extension of the :ref:`create_spline_example`. |
| 11 |
|
| 12 |
""" |
| 13 |
|
| 14 |
import numpy as np |
| 15 |
import pyvista as pv |
| 16 |
|
| 17 |
# %% |
| 18 |
# Create a spline |
| 19 |
# ~~~~~~~~~~~~~~~ |
| 20 |
# Create a spline using :func:`pyvista.Spline`. |
| 21 |
|
| 22 |
# Make points along a spline |
| 23 |
theta = np.linspace(-1 * np.pi, 1 * np.pi, 100) |
| 24 |
z = np.linspace(2, -2, 100) |
| 25 |
r = z**2 + 1 |
| 26 |
x = r * np.sin(theta) |
| 27 |
y = r * np.cos(theta) |
| 28 |
points = np.column_stack((x, y, z)) |
| 29 |
|
| 30 |
# Create a spline. This automatically computes arc_length, which is the |
| 31 |
# distance along the line. |
| 32 |
spline = pv.Spline(points, 1000) |
| 33 |
spline.point_data |
| 34 |
|
| 35 |
|
| 36 |
# %% |
| 37 |
# Determine the coordinates matching distance along a spline |
| 38 |
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 39 |
# Here we write a simple function that gets the closest point matching a distance along a |
| 40 |
# spline and then generate labels for those points. |
| 41 |
|
| 42 |
|
| 43 |
def get_point_along_spline(distance): |
| 44 |
"""Return the closest point on the spline given a length along the spline.""" |
| 45 |
idx = np.argmin(np.abs(spline.point_data['arc_length'] - distance)) |
| 46 |
return spline.points[idx] |
| 47 |
|
| 48 |
|
| 49 |
# distances along the spline we're interested in |
| 50 |
dists = [0, 4, 8, 11] |
| 51 |
|
| 52 |
# make labels |
| 53 |
labels = [] |
| 54 |
label_points = [] |
| 55 |
for dist in dists: |
| 56 |
point = get_point_along_spline(dist) |
| 57 |
labels.append(f'Dist {dist}: ({point[0]:.2f}, {point[1]:.2f}, {point[2]:.2f})') |
| 58 |
label_points.append(point) |
| 59 |
|
| 60 |
labels |
| 61 |
|
| 62 |
# %% |
| 63 |
# Plot with Labels |
| 64 |
# ~~~~~~~~~~~~~~~~ |
| 65 |
# Plot the spline with labeled points |
| 66 |
|
| 67 |
# sphinx_gallery_start_ignore |
| 68 |
# depth field modification does not seem to work in interactive mode |
| 69 |
PYVISTA_GALLERY_FORCE_STATIC = True |
| 70 |
# sphinx_gallery_end_ignore |
| 71 |
|
| 72 |
pl = pv.Plotter() |
| 73 |
pl.add_mesh(spline, scalars='arc_length', render_lines_as_tubes=True, line_width=10) |
| 74 |
pl.add_point_labels( |
| 75 |
label_points, |
| 76 |
labels, |
| 77 |
always_visible=True, |
| 78 |
point_size=20, |
| 79 |
render_points_as_spheres=True, |
| 80 |
) |
| 81 |
pl.show_bounds() |
| 82 |
pl.show_axes() |
| 83 |
pl.camera_position = 'xz' |
| 84 |
pl.show() |
| 85 |
# %% |
| 86 |
# .. tags:: plot |