【问题标题】:Matplotlib surface plot unintuitive triangulationMatplotlib 曲面图不直观的三角剖分
【发布时间】:2018-01-20 10:54:26
【问题描述】:

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

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 的形状都是相等的,并且是 2D 的。

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

我在下面提供了一个散点图来显示数据在没有表面的情况下的样子:

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

感谢您的帮助。

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

【问题讨论】:

    标签: python python-2.7 matplotlib plot


    【解决方案1】:

    确保在调用meshgrid之前对dealer_sumsplayer_sums进行了排序, 否则,线框中连接的点也会乱序:

    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_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. ]])
    

    【讨论】:

      猜你喜欢
      • 2015-07-09
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 2020-09-23
      • 2019-09-28
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      相关资源
      最近更新 更多