如何在Python中使用“matplotlib”在表面上创建一条线

3
我想在一个表面上(粉色表面)画两条线来代表这个粉色表面的两条切割线和两个二维平面(x = y 和 x = -y),就像下面图片中的蓝色线一样。有人知道如何做吗?

The illustrating figure

生成粉色表面的代码如下:
import numpy as NP
import matplotlib.pyplot as PLT

def f(x1, x2):
    return 0.5 * x1 + 0.6 * x2 + 0.2 * x1 * x1 + 0.1 * x1 * x2 + 0.3 * x2 * x2 + 4

x = NP.linspace(-3, 3, 100)
y = NP.linspace(-3, 3, 100)
xx, yy = NP.meshgrid(x,y)
z = f(xx, yy)

# set up the figure
fig = PLT.figure()
ax = fig.gca(projection='3d')
ax.set_xlim(-3, 3)
ax.set_ylim(3, -3)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")

# plot the figure
ax.plot_surface(xx, yy, z, cmap="spring", alpha = 0.7)

# add the x=y line to the ground plane
ax.plot([-3, 3], [-3, 3], color = 'grey', linewidth = 1, linestyle='dashed')

# add the x=-y line to the ground plane
ax.plot([3, -3], [-3, 3], color = 'grey', linewidth = 1, linestyle='dashed')

PLT.show()
1个回答

3

您可以使用plot(x, -x, f(x, -x))plot(x, x, f(x, x))来绘制曲线。请注意,matplotlib无法完全隐藏部分被其他元素遮挡的元素。

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

def f(x1, x2):
    return 0.5 * x1 + 0.6 * x2 + 0.2 * x1 * x1 + 0.1 * x1 * x2 + 0.3 * x2 * x2 + 4

x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
xx, yy = np.meshgrid(x,y)
z = f(xx, yy)

# set up the figure
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_xlim(-3, 3)
ax.set_ylim(3, -3)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")

# plot the figure
ax.plot_surface(xx, yy, z, cmap="spring", alpha = 0.7)

# add the x=y line to the ground plane
ax.plot([-3, 3], [-3, 3], color='grey', linewidth=1, linestyle='dashed')

# add the x=-y line to the ground plane
ax.plot([3, -3], [-3, 3], color='grey', linewidth=1, linestyle='dashed')

ax.plot(x, x, f(x, x), color='dodgerblue')
ax.plot(x, -x, f(x, -x), color='dodgerblue')

plt.show()

enter image description here


哥们,你的解决方案太棒了!非常感谢。我还有一个问题,你能再帮我一下吗?https://stackoverflow.com/questions/60517183/how-to-plot-a-slicing-plane-with-a-surface-with-matplotlib-in-python - wh41e
看起来其他问题已经得到了令人满意的回答。可选地,您可以将x轴分别标记为x,yx,-y,并将y轴标记为z,以便与3D图表保持一致。 - JohanC
你点赞了吗?你知道如何标记为(X,Y)或(X,-Y)吗? - wh41e
plt.xlabel('(X,-Y)'); plt.ylabel('Z') - JohanC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接