Python中使用箭头图函数可视化磁场

1 投票
2 回答
4048 浏览
提问于 2025-04-16 12:07

我想用quiver函数来可视化一根电线的磁场。

#Calculation of a magnetic field of a wire

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from pylab import *

I = 100000000000
constant = 1e-7/(4*np.pi)

# wire elements; always lenght one
coord = [(10,10,0), (11,10,0), (12,10,0), (13,10,0), (14,10,0), (15,10,0), (16,10,0), (17,10,0), (18,10,0),
         (19,10,0), (19,11,0), (19,12,0), (19,13,0)]

xwidth = 3
ywidth = 3
z = 1
b = np.zeros((xwidth,ywidth))

# calculate the b-field
def bfield(x,y,z,c):
    for x in range(xwidth):
        for y in range(ywidth):
            # number of wire elements
            for i in range(1,12):
                rx = x-(coord[i][0]+coord[i+1][0])/2.
                ry = y-(coord[i][1]+coord[i+1][1])/2.
                rz = z * 1.0 # = z-0
                r = (rx**2+ry**2+rz**2)**0.5 # distance r between field and middle of the wire
                dl = np.array([(coord[i+1][0]-coord[i][0]), (coord[i+1][1]-coord[i][1]), 0])
                bb = np.cross(dl, np.array([rx,ry,rz]))
                e = constant*I*bb/r**3
                print e
                #print e[0], e[1]
                b[x,y] += e[c]  # EDIT
    return b

X,Y = meshgrid(arange(0,xwidth,1),arange(0,ywidth,1))
U = bfield(X,Y,z,0)
V = bfield(X,Y,z,1)
quiver(X,Y,U,V)
xlim(0,xwidth)
ylim(0,ywidth)
show()

编辑2:我该如何在图中绘制坐标线?
编辑3:我想使用quiver,但它不起作用。

2 个回答

0
ValueError: too many values to unpack

这句话的意思是,你在等式的右边有更多的值,而左边的变量却比较少。

1

看起来quiver目前只支持二维图表,但你可以通过将多个二维层叠加到一个三维图表中来实现三维效果。你可以参考我的示例,看看如何制作这些层。

撰写回答