matplotlib 如何控制向量的长度

dphi5xsq  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(124)
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter 

fig = plt.figure(dpi = 200)
ax = fig.subplots()
a = 4
t = np.linspace(-16,16,33)
t2 = np.linspace(-16,16,32) 
x,y=np.meshgrid(t,t2)

xx = 1*(x-a)/(((x-a)*(x-a)+y*y)**(1.5))-(x+a)/(((x+a)*(x+a)+y*y)**(1.5))
yy = 1*y/(((x-a)*(x-a)+y*y)**(1.5))-y/(((x+a)*(x+a)+y*y)**(1.5))

r = np.power(np.add(np.power(xx,2), np.power(yy,2)),0.5)

line1 = ax.quiver(x,y,xx/r,yy/r,pivot='middle',scale=4,color = 'white')

line2 = ax.scatter([-4,4],[0,0],color = 'r')
line3 = ax.scatter([-4,4],[0,0])
ax.set_aspect(0.5)
ax.set_facecolor('black')

def updata(frame):
    a = 8*np.sin(np.pi*(frame+1)/150)
    xx = 15*((x-a)/(((x-a)*(x-a)+y*y)**(1.5))-(x+a)/(((x+a)*(x+a)+y*y)**(1.5)))
    yy = 15*(y/(((x-a)*(x-a)+y*y)**(1.5))-y/(((x+a)*(x+a)+y*y)**(1.5)))
    r = np.power(np.add(np.power(xx,2), np.power(yy,2)),0.5)
    line1.set_UVC(xx,yy)
    line2.set_offsets([a,0])
    line3.set_offsets([-a,0])
    return line1 and line2 and line3

ani = FuncAnimation(fig,func=updata,frames=300,interval = 30)

plt.show()

enter image description here这是电场动态图。
电子附近的矢量长度太长,如何缩短过长矢量的长度?

laik7k3q

laik7k3q1#

line1 = ax.quiver(x,y,xx,yy,scale_units='xy',pivot='middle')

并在updata中添加以下代码:

r = np.power(np.add(np.power(xx,2), np.power(yy,2)),0.5)
for i in range(32):
    for j in range(33):
        if xx[i][j]**2+yy[i][j]**2>0.0081:
            xx[i][j]=0.09*xx[i][j]/r[i][j]
            yy[i][j]=0.09*yy[i][j]/r[i][j]

相关问题