如何使用Matplotlib在python中绘制矢量

发布于 2021-01-29 15:06:45

我正在学习线性代数课程,我想可视化正在使用的向量,例如向量加法,法向向量等。

例如:

V = np.array([[1,1],[-2,2],[4,-7]])

在这种情况下,我想绘制3个向量V1 = (1,1), M2 = (-2,2), M3 = (4,-7)

然后,我应该能够添加V1,V2来绘制一个新的向量V12(全部合并在一个图中)。

当我使用以下代码时,情节与预期不符

import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])

print("vector:1")
print(M[0,:])
# print("vector:2")
# print(M[1,:])
rows,cols = M.T.shape
print(cols)

for i,l in enumerate(range(0,cols)):
    print("Iteration: {}-{}".format(i,l))
    print("vector:{}".format(i))
    print(M[i,:])
    v1 = [0,0],[M[i,0],M[i,1]]
    # v1 = [M[i,0]],[M[i,1]]
    print(v1)
    plt.figure(i)
    plt.plot(v1)
    plt.show()
关注者
0
被浏览
104
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    多亏了每个人,您的每个帖子对我都有很大帮助。
    对于我的问题,rbierman代码非常简单,我做了一些修改,并创建了一个函数来绘制给定数组中的向量。我希望看到任何进一步改进建议。

    import numpy as np
    import matplotlib.pyplot as plt
    def plotv(M):
        rows,cols = M.T.shape
        print(rows,cols)
    
        #Get absolute maxes for axis ranges to center origin
        #This is optional
        maxes = 1.1*np.amax(abs(M), axis = 0)
        colors = ['b','r','k']
        fig = plt.figure()
        fig.suptitle('Vectors', fontsize=10, fontweight='bold')
    
        ax = fig.add_subplot(111)
        fig.subplots_adjust(top=0.85)
        ax.set_title('Vector operations')
    
        ax.set_xlabel('x')
        ax.set_ylabel('y')
    
        for i,l in enumerate(range(0,cols)):
            # print(i)
            plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.2,head_length=0.1,zorder=3)
    
            ax.text(M[i,0],M[i,1], str(M[i]), style='italic',
                bbox={'facecolor':'red', 'alpha':0.5, 'pad':0.5})
    
        plt.plot(0,0,'ok') #<-- plot a black point at the origin
        # plt.axis('equal')  #<-- set the axes to the same scale
        plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
        plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
    
        plt.grid(b=True, which='major') #<-- plot grid lines
        plt.show()
    
    r = np.random.randint(4,size=[2,2])
    print(r[0,:])
    print(r[1,:])
    r12 = np.add(r[0,:],r[1,:])
    print(r12)
    plotv(np.vstack((r,r12)))
    

    在随机向量上执行向量加法



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看