首页 > 解决方案 > 如何在给定长度的曲线的每个点上绘制法线向量?

问题描述

如何在给定长度的曲线的每个点上绘制法线向量?

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [8, 8]

x = np.linspace(-1, 1, 100)
y = x**2
ax.set_ylim(-0.3, 1.06)
ax.plot(x, y)

plt.show()

标签: pythonpython-3.xnumpymatplotlibgeometry

解决方案


import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [8, 8]

x = np.linspace(-1, 1, 100)
y = x**2

# Calculating the gradient
L=.1 # gradient length
grad = np.ones(shape = (2, x.shape[0]))
grad[0, :] = -2*x
grad /= np.linalg.norm(grad, axis=0)  # normalizing to unit vector

nx = np.vstack((x - L/2 * grad[0], x + L/2 * grad[0]))
ny = np.vstack((y - L/2 * grad[1], y + L/2 * grad[1]))

# ax.set_ylim(-0.3, 1.06)
ax.plot(x, y)
ax.plot(nx, ny, 'r')
ax.axis('equal')

plt.show()

在此处输入图像描述


推荐阅读