python怎么用matplotlib画_如何使用Matplotlib在python中绘制矢量

I am taking a course on linear algebra and I want to visualize the vectors in action, such as vector addition, normal vector, so on.

For instance:

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

In this case I want to plot 3 vectors V1 = (1,1), M2 = (-2,2), M3 = (4,-7).

Then I should be able to add V1,V2 to plot a new vector V12(all together in one figure).

when I use the following code, the plot is not as intended

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

解决方案

Thanks to everyone, each of your posts helped me a lot.

rbierman code was pretty straight for my question, I have modified a bit and created a function to plot vectors from given arrays. I'd love to see any suggestions to improve it further.

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') #

# plt.axis('equal') #

plt.xlim([-maxes[0],maxes[0]]) #

plt.ylim([-maxes[1],maxes[1]]) #

plt.grid(b=True, which='major') #

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值