我试图用Numpy和Matplotlib可视化一个2D平面切割一个3D图形,以解释偏导数的直觉。
具体来说,我使用的函数是J(θ1,θ2)= θ1^2 + θ2^2,我想在θ2=0处绘制一个θ1-J(θ1,θ2)平面。
我已经设法用下面的代码绘制了一个2D平面,但是2D平面和3D图形的叠加不太正确,2D平面稍微偏离,因为我希望平面看起来像是在θ2=0处切割3D。
如果我能借用你的专业知识就太好了,谢谢。
def f(theta1, theta2):
return theta1**2 + theta2**2
fig, ax = plt.subplots(figsize=(6, 6),
subplot_kw={'projection': '3d'})
x,z = np.meshgrid(np.linspace(-1,1,100), np.linspace(0,2,100))
X = x.T
Z = z.T
Y = 0 * np.ones((100, 100))
ax.plot_surface(X, Y, Z)
r = np.linspace(-1,1,100)
theta1_grid, theta2_grid = np.meshgrid(r,r)
J_grid = f(theta1_grid, theta2_grid)
ax.contour3D(theta1_grid,theta2_grid,J_grid,500,cmap='binary')
ax.set_xlabel(r'$\theta_1$',fontsize='large')
ax.set_ylabel(r'$\theta_2$',fontsize='large')
ax.set_zlabel(r'$J(\theta_1,\theta_2)$',fontsize='large')
ax.set_title(r'Fig.2 $J(\theta_1,\theta_2)=(\theta_1^2+\theta_2^2)$',fontsize='x-large')
plt.tight_layout()
plt.show()
这是代码输出的图像:
1条答案
按热度按时间jecbmhm31#
正如@ImportanceOfBeingErnest在评论中指出的那样,您的代码很好,但matplotlib有一个2d引擎,因此3d图很容易显示奇怪的工件。特别是,对象一次渲染一个,所以两个3d对象通常要么完全在另一个前面,要么完全在另一个后面,这使得使用matplotlib几乎不可能实现互锁3d对象的可视化。
我个人的替代建议是mayavi(难以置信的灵活性和可视化,相当陡峭的学习曲线),但是我想展示一个技巧,通常可以完全消除问题。这个想法是把你的两个独立的对象变成一个单一的使用一个无形的桥梁之间的表面。这种方法可能的缺点是
1.需要将两个曲面都作为曲面而不是
contour3D
进行绘制,并且1.输出在很大程度上依赖于透明度,因此您需要一个可以处理该问题的后端。
免责声明:我从now-defunct Stack Overflow Documentation project的matplotlib主题的贡献者那里学到了这个技巧,但不幸的是,我不记得那个用户是谁。
为了在您的用例中使用这个技巧,我们必须将
contour3D
调用转换为另一个plot_surface
调用。我不认为这是整体的坏;如果您发现生成的图形有太多的面而无法交互使用,则可能需要重新考虑剪切平面的密度。我们还必须明确定义一个逐点的颜色Map表,其Alpha通道在两个曲面之间提供透明的桥梁。因为我们需要将两个表面缝合在一起,所以表面的至少一个“面内”尺寸必须匹配;在这种情况下,我确保沿着“y”的点在两种情况下相同。结果从两个Angular 来看:
如你所见,结果相当不错。您可以开始尝试使用曲面的各个透明度,以查看是否可以使该横截面更加可见。也可以将桥的不透明度切换为1,以查看曲面实际缝合在一起的方式。总而言之,我们要做的就是获取现有的数据,确保它们的大小匹配,并定义显式的颜色Map表和曲面之间的辅助桥梁。