matplotlib 尝试获取3D中表面上的cmap以匹配其子级集的cmap

gj3fmq9x  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(139)

我试图让三维表面的颜色与右边对应的子层集的颜色相匹配(如下图所示)。特别是,我希望右边图像中间的小值为蓝色,大值为红色。以下是我的代码:

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

# Define the function to plot
def f(x, y):
    return x**2 + y**2

# Generate data for the x, y, and z coordinates
x = np.linspace(-6, 6, 100)
y = np.linspace(-6, 6, 100)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

# Create a 3D figure and a contour plot side by side
fig = plt.figure(figsize=(10, 4))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122)

# Plot the surface on the left subplot
surf = ax1.plot_surface(X, Y, Z, cmap='jet')

# Plot the contour on the right subplot
for a in range(1,30,5):
    contour_levels = np.arange(-a, a, 0.1)
    ax2.contourf(X, Y, Z, levels=contour_levels, cmap='jet')
    plt.pause(.001)

# Add labels and title to both subplots
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_zlabel('z')
ax1.set_title('3D Plot of f(x, y) = sin(sqrt(x^2 + y^2))')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('Level Set Contour Plot of f(x, y) = x^2 + y^2')
surf.set_edgecolors(surf.to_rgba(surf._A))

# Show the plot
plt.show()

下面是输出:

有没有人发现任何bug或者看看我该如何修复它?我怀疑contourf函数实际上可能没有给我想要的子级集合。为了完整起见,子级集合的意思是:
${x\in\mathbb {R}:f(x)\le a} $
还有,PS这个网站真的不接受乳胶吗?

ggazkfy8

ggazkfy81#

我认为问题出在你的等高线水平范围上。如果,而不是:

# Plot the contour on the right subplot
for a in range(1,30,5):
    contour_levels = np.arange(-a, a, 0.1)
    ax2.contourf(X, Y, Z, levels=contour_levels, cmap='jet')
    plt.pause(.001)

您需要:

contour_levels = np.arange(Z.min(), Z.max(), 0.1)
ax2.contourf(X, Y, Z, cmap='jet', levels=contour_levels)

它应给予:

相关问题