Matplotlib - 同时在 3D 中绘制平面和点

Matplotlib - Plot a plane and points in 3D simultaneously

我正在尝试使用 Matplotlib 在 3D 中同时绘制一个平面和一些点。 我没有错误只是点不会出现。 我可以在不同时间绘制一些点和平面,但绝不能同时绘制。 代码的一部分看起来像:

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

您需要告诉坐标轴您想要新绘图 添加 到坐标轴上的当前绘图而不是覆盖它们。为此,您需要使用 axes.hold(True)

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

更新

作为@tcaswell pointed out in the comments, they are considering discontinuing support for hold. As a result, a better approach may be to use the axes directly to add more plots as in

只是添加到@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')

只是在数学部分(以及它是如何工作的)做更多的阐述,可能对某些人有用,单位法向量 n 包含一个点的平面方程a显示如下:

因此此处的平面方程为 x + y + 2*z = 9 并且可以使用以下代码简单地绘制给定平面:

# create the figure
fig = plt.figure()

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

xx, yy = np.meshgrid(range(10), range(10))
z = (9 - xx - yy) / 2 

# plot the plane
ax.plot_surface(xx, yy, z, alpha=0.5)

plt.show()

scatter()

绘制点很简单