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

标签 python python-2.7 matplotlib plot

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

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 matplotlibSimplest way to plot 3d surface given 3d points),似乎一个常见的问题是 x 和 y 坐标不规则,但如果我理解正确,我认为我的已经通过调用 np.meshgrid?

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

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

感谢您的帮助。

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

最佳答案

确保 dealer_sumsplayer_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()

enter image description here

在左侧,dealer_sumsplayer_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. ]])

关于python - Matplotlib 曲面图不直观的三角剖分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45643384/

相关文章:

python - 添加带条件着色的水平线

python - basemap 上不同的地 block 大小

python - seaborn 中的条形图

python - 使用 Connexion 时访问像 before_request 这样的 Flask 方法

python - 当列表中有两个连续相似的数字时,如何打破循环?

Python参数语法错误: invalid syntax

html - Selenium - XPath - 通过 innerHTML 搜索元素

python - 在 matplotlib 中对齐 TeX 方程

python - 无法使用 pip 安装 Scipy

python - 通过广播系列更新数据帧值