简体   繁体   English

使用带有内部随机点数的matplotlib 3D图绘制椭圆体时出错:Python

[英]Error while plotting an ellipsoid using matplotlib 3D plot with random number of points inside: Python

While plotting an ellipsoid using axes3D, I met with an error 在使用axes3D绘制椭圆体时,遇到一个错误

TypeError: unbound method plot() must be called with Axes3D instance as first argument (got ndarray instance instead) TypeError:未绑定的方法plot()必须以Axes3D实例作为第一个参数来调用(取而代之的是ndarray实例)

I need to plot the ellipsoid with random number of points inside. 我需要绘制椭圆形,里面的点数是随机的。 SO i used random module. 所以我用随机模块。 But I couldn't identify the reason for such an error. 但我无法确定发生此类错误的原因。 The program is given below. 该程序如下。

import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import *

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 1000000
a = input("Enter the value of semi major axis: \n")
b = input("Enter the value of semi minor axis: \n")
c = input("Enter the value of c \n")
x = random.uniform(-a, a, n)
y = random.uniform(-b, b, n)
z = random.uniform(-c, c, n)
r = (x ** 2 / a ** 2) + (y ** 2 / b ** 2) + (z ** 2 / c ** 2)
rd = r[:] <= 1
xd = x[rd]
yd = y[rd]
zd = z[rd]
Axes3D.plot3D(xd, yd, zd, "*")
plot.show()

May be there some errors. 可能有一些错误。 I am a beginner and please help me. 我是初学者,请帮助我。

Your import random cannot work, leading to problems even before you try to plot your cloud of points, because random.uniform has a different signature from what you use. 您的import random不能正常工作,甚至在尝试绘制点云之前都会导致问题,因为random.uniform的签名与您使用的签名不同。

I suppose that the real statement you use is from numpy import random ... 我想您使用的真实语句from numpy import random ...

Further, the standard way (and there is a reason) to import the 3d capabilities is from mpl_toolkits.mplot3d import Axes3D — this modifies the definition of the axes object, and that's all you need. 此外,导入3d功能的标准方法(也是有原因的) from mpl_toolkits.mplot3d import Axes3D -这修改了from mpl_toolkits.mplot3d import Axes3D对象的定义,这就是您所需要的。

Finally, you use the .plot() method when what you really need is .scatter() , that doesn't draw the lines connecting the individual points. 最后,当真正需要的是.scatter()时,可以使用.plot()方法,该方法不会绘制连接各个点的线。

My version of what you're trying to accomplish is as follows (note that I use the modified ax object, not Axes3D ...) 我要完成的工作的版本如下(请注意,我使用的是修改后的ax对象,而不是Axes3D ...)

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from numpy.random import uniform

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n, a, b, c = 2000, 10.0, 6.0, 20.0
x, y, z = [uniform(-d, d, n) for d in (a, b, c)]
inside =  ((x/a)**2 + (y/b)**2 + (z/c)**2) <= 1.0

ax.scatter(x[inside], y[inside], z[inside])

plt.show()

样例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM