Skip to main content
 首页 » 编程设计

python之Matplotlib 曲面图不直观的三角剖分

2025年02月15日7小虾米

我有以下生成曲面图的代码,但它没有达到我的预期。

xx, yy = np.meshgrid(dealer_sums, player_sums) 
    def getter(dealer_sum, player_sum): 
        state = (dealer_sum, player_sum) 
        return self.get_value(state) 
    z = np.vectorize(getter) 
    zz = z(xx,yy) 
 
    fig = plt.figure() 
    ax  = fig.add_subplot(111, projection='3d') 
    ax.plot_wireframe(xx,yy, zz) 

仅供引用,xx、yy 和 zz 的形状都是相等的和二维的。

从其他帖子来看(surface plots in matplotlib;Simplest way to plot 3d surface given 3d points),似乎一个常见的问题是 x 和 y 坐标不规则,但如果我理解正确,我认为我的已经通过调用 np.meshgrid?

我在下面提供了一个散点图来显示没有曲面的数据:

这就是调用 plot_wireframe 的样子:
我画了一些我没想到的线。我的问题是,是否有可能摆脱这些线条并创建一个看起来像这样的表面?

感谢您的帮助。

编辑:这是 XY 网格的散点图,表明它是规则的:

请您参考如下方法:

确保 dealer_sums 和 player_sums 在调用 meshgrid 之前排序, 否则,线框中连接的点也会乱序:

import numpy as np 
import matplotlib.pyplot as plt 
import mpl_toolkits.mplot3d.axes3d as axes3d 
 
def z(xx, yy): 
    return -xx + (yy-18)**2 
 
dealer_sums = [1, 5, 9] 
player_sums = [14, 17, 21, 14] 
 
fig = plt.figure() 
ax = fig.add_subplot(1, 2, 1, projection='3d') 
ax2 = fig.add_subplot(1, 2, 2, projection='3d') 
 
xx, yy = np.meshgrid(dealer_sums, player_sums) 
zz = z(xx, yy) 
ax.plot_wireframe(xx, yy, zz) 
 
xx2, yy2 = np.meshgrid(np.unique(dealer_sums), np.unique(player_sums)) 
zz2 = z(xx2, yy2) 
 
ax2.plot_wireframe(xx2, yy2, zz2) 
plt.show() 

在左侧,dealer_sums 和 player_sums 未排序。 在右侧,它们已排序。


np.unique 按排序顺序返回唯一值。上面,确实是最重要的排序,但是用重复的坐标制作网格没有意义,所以唯一性是一个额外的好处。


请注意,meshgrid 不一定返回规则网格。 如果 dealer_sums 和/或 player_sums 是不规则的,那么 xx 和/或 yy 也是不规则的。

In [218]: xx, yy = np.meshgrid([0,2,1], [0, .5, 10]) 
 
In [219]: xx 
Out[219]:  
array([[0, 2, 1], 
       [0, 2, 1], 
       [0, 2, 1]]) 
 
In [220]: yy 
Out[220]:  
array([[  0. ,   0. ,   0. ], 
       [  0.5,   0.5,   0.5], 
       [ 10. ,  10. ,  10. ]])