如何在python中使用“ matplotlib”在表面上创建线

问题描述 投票:0回答:1

我想在一个表面(粉红色表面)上绘制两条线,以代表该粉红色表面的两条切割线和两个2d平面(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()
python matplotlib plot 3d surface
1个回答
1
投票

您可以只使用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

© www.soinside.com 2019 - 2024. All rights reserved.