Matplotlib - 在三维空间中同时绘制平面和点

2024-09-28 17:22:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Matplotlib同时绘制一个平面和一些三维点。 我没有错误,只是这一点不会出现。 我可以在不同的时间绘制一些点和平面,但不能同时绘制。 代码部分如下:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

point  = np.array([1, 2, 3])
normal = np.array([1, 1, 2])

point2 = np.array([10, 50, 50])

# a plane is a*x+b*y+c*z+d=0
# [a,b,c] is the normal. Thus, we have to calculate
# d and we're set
d = -point.dot(normal)

# create x,y
xx, yy = np.meshgrid(range(10), range(10))

# calculate corresponding z
z = (-normal[0] * xx - normal[1] * yy - d) * 1. /normal[2]

# plot the surface
plt3d = plt.figure().gca(projection='3d')
plt3d.plot_surface(xx, yy, z, alpha=0.2)


#and i would like to plot this point : 
ax.scatter(point2[0] , point2[1] , point2[2],  color='green')

plt.show()

Tags: theimportplotisasnp绘制plt
2条回答

您需要告诉轴,您希望新的绘图添加到轴上的当前绘图,而不是覆盖它们。为此,您需要使用^{}

# plot the surface
plt3d = plt.figure().gca(projection='3d')
plt3d.plot_surface(xx, yy, z, alpha=0.2)

# Ensure that the next plot doesn't overwrite the first plot
ax = plt.gca()
ax.hold(True)

ax.scatter(points2[0], point2[1], point2[2], color='green')

enter image description here

更新

正如@tcaswell在评论中指出的,他们正在考虑停止对hold的支持。因此,更好的方法可能是直接使用轴来添加更多的绘图,如@tom's answer.

为了补充@suever的答案,您没有理由不创建Axes,然后在其上绘制曲面和散点。那么就不需要使用ax.hold()

# Create the figure
fig = plt.figure()

# Add an axes
ax = fig.add_subplot(111,projection='3d')

# plot the surface
ax.plot_surface(xx, yy, z, alpha=0.2)

# and plot the point 
ax.scatter(point2[0] , point2[1] , point2[2],  color='green')

相关问题 更多 >