Skip to main content
 首页 » 编程设计

python mpl : how to plot a point on a graph of 3D vectors, 和箭头

2024年10月17日8txw1958

我有以下代码来生成一个三角形(从一些线)和一个 3D 图形中的矢量:

from mpl_toolkits.mplot3d import axes3d 
import matplotlib.pyplot as plt 
import numpy as np 
 
import sys 
 
# D is the viewing direction. 
# P is the "eye" point. 
# A, B, and C are the points of the Triangle being tested against. 
 
# make a shear matrix from the D vector. 
def make_shear(d): 
    print [1, 0, -d[0]/d[2] ]; 
    print [1, 0, -d[1]/d[2]]; 
    print [0, 0, 1/d[2]] ; 
    return np.array([ [1, 0, -d[0]*1.0/d[2] ], [0, 1, -d[1]*1.0/d[2]], [0, 0, 1.0/d[2]] ]); 
 
def draw_line(ax, A, B, c): 
    ax.plot([A[0], B[0]], [A[1],B[1]],[A[2],B[2]], color=c) 
 
plt.close('all'); 
 
fig1 = plt.figure(); 
 
ax = fig1.add_subplot(111, projection='3d') 
 
P = np.array([3, 4, 2]); 
P1 = np.array([1, 5, 7]); 
D = P1 - P; 
M = make_shear(D); 
 
print "D = ", D 
#print D[0]; 
 
print "M = "; 
print M; 
 
Dp = M.dot(D); 
 
A =np.array([-5, 3, 5]); 
B =np.array([1, 4, 10]); 
C =np.array([-5, 5, 5]); 
 
Ap = M.dot(A-P); 
Bp = M.dot(B-P); 
Cp = M.dot(C-P); 
 
U = np.dot(Dp, np.cross(Cp, Bp)); 
V = np.dot(Dp, np.cross(Ap, Cp)); 
W = np.dot(Dp, np.cross(Bp, Ap)); 
print "U = ", U; 
print "V = ", V; 
print "W = ", W; 
 
ax = fig1.add_subplot(111, projection='3d') 
ax.set_xlabel('X axis') 
ax.set_ylabel('Y axis') 
ax.set_zlabel('Z axis') 
 
draw_line(ax, A, B, 'g'); 
draw_line(ax, B, C, 'g'); 
draw_line(ax, C, A, 'g'); 
sf = 5; # scale factor, to make the direction more obvious...not sure this works. 
ax.quiver(P[0], P[1], P[2], sf*D[0], sf*D[1], sf*D[2]); # head_width=0.05, head_length=0.1, fc='k', ec=ki"); 
 
b = 10; 
ax.set_xlim([-b, b]); 
ax.set_ylim([-b, b]); 
ax.set_zlim([-b, b]); 
plt.show(); 
  1. 我想在图形中添加一个点,比如 P,作为一个红色的小球体。
  2. 我想在 quiver 语句中绘制的向量的头部添加一个箭头。

做这两件事最直接的方法是什么?

请您参考如下方法:

  1. 在您的 x.quiver... 行之后添加以下行。

    ax.scatter(P[0], P[1], P[2], c='r') 
    
  2. 在您的 x.quiver... 行之后添加以下行。

    v = [0, 1, 0] 
    end_v = P + v 
    ax.quiver(end_v[0], end_v[1], end_v[2], v[0], v[1], v[2])