繁体   English   中英

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

[英]How to plot normal vectors in each point of the curve with a given length?

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

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()
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()

在此处输入图像描述

对于 plot 的normals ,您需要计算每个点的斜率; 从那里,您可以得到可以旋转pi/2的切线向量。

在此处输入图像描述

这是使用 python i/o np 的一种方法,起初它可能更容易理解。

更改长度将调整法线的大小以与 plot 正确缩放。

import matplotlib.pyplot as plt
import numpy as np
import math

def get_normals(length=.1):
    
    for idx in range(len(x)-1):
        x0, y0, xa, ya = x[idx], y[idx], x[idx+1], y[idx+1]
        dx, dy = xa-x0, ya-y0
        norm = math.hypot(dx, dy) * 1/length
        dx /= norm
        dy /= norm
        
        ax.plot((x0, x0-dy), (y0, y0+dx))    # plot the normals


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)
get_normals()


plt.show()

或更长的法线,向下: get_normals(length=-.3) (使用ax.set_aspect('equal')保持角度)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM