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

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

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

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from mpl_toolkits import mplot3d
  4. # Define the function to plot
  5. def f(x, y):
  6. return x**2 + y**2
  7. # Generate data for the x, y, and z coordinates
  8. x = np.linspace(-6, 6, 100)
  9. y = np.linspace(-6, 6, 100)
  10. X, Y = np.meshgrid(x, y)
  11. Z = f(X, Y)
  12. # Create a 3D figure and a contour plot side by side
  13. fig = plt.figure(figsize=(10, 4))
  14. ax1 = fig.add_subplot(121, projection='3d')
  15. ax2 = fig.add_subplot(122)
  16. # Plot the surface on the left subplot
  17. surf = ax1.plot_surface(X, Y, Z, cmap='jet')
  18. # Plot the contour on the right subplot
  19. for a in range(1,30,5):
  20. contour_levels = np.arange(-a, a, 0.1)
  21. ax2.contourf(X, Y, Z, levels=contour_levels, cmap='jet')
  22. plt.pause(.001)
  23. # Add labels and title to both subplots
  24. ax1.set_xlabel('x')
  25. ax1.set_ylabel('y')
  26. ax1.set_zlabel('z')
  27. ax1.set_title('3D Plot of f(x, y) = sin(sqrt(x^2 + y^2))')
  28. ax2.set_xlabel('x')
  29. ax2.set_ylabel('y')
  30. ax2.set_title('Level Set Contour Plot of f(x, y) = x^2 + y^2')
  31. surf.set_edgecolors(surf.to_rgba(surf._A))
  32. # Show the plot
  33. plt.show()

下面是输出:

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

ggazkfy8

ggazkfy81#

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

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

您需要:

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

它应给予:

相关问题