Python Matplotlib - 同时在 3D 中绘制平面和点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36060933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib - Plot a plane and points in 3D simultaneously
提问by user3601754
I m trying to plot simultaneously a plane and some points in 3D with Matplotlib. I have no errors just the point will not appear. I can plot at different times some points and planes but never at same time. The part of the code looks like :
我正在尝试使用 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()
采纳答案by Suever
You will need to tell the axes that you want new plots to addto the current plots on the axes rather than overwriting them. To do this, you will need to use axes.hold(True)
您需要告诉轴您希望将新图添加到轴上的当前图而不是覆盖它们。为此,您需要使用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')
UPDATE
更新
As @tcaswellpointed 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 @tom's answer.
正如@tcaswell在评论中指出的那样,他们正在考虑停止对hold
. 因此,更好的方法可能是直接使用坐标轴来添加更多图,如@tom 的答案。
回答by tmdavison
Just to add to @suever's answer, you there's no reason why you can't create the Axes
and then plot both the surface and the scatter points on it. Then there's no need to use ax.hold()
:
只是为了添加@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')