【问题标题】:How to plot normal vectors in each point of the curve with a given length?如何在给定长度的曲线的每个点上绘制法线向量?
【发布时间】:2020-12-15 17:40:17
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x numpy matplotlib geometry


    【解决方案1】:
    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()
    

    【讨论】:

      【解决方案2】:

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

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

      更改长度将调整法线的大小以正确缩放您的绘图。

      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') 保持角度)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多