【问题标题】:Plot Array as Grid with values in Python在 Python 中使用值将数组绘制为网格
【发布时间】:2021-10-25 06:35:02
【问题描述】:

我需要绘制一个数组。我尝试了 Joe Kington (Show the values in the grid using matplotlib) 的代码,但我得到了错误:

for (i, j), z in np.ndenumerate(array):

#ValueError: too many values to unpack (expected 2). 

有人可以帮我找出错误吗?

这是我试过的代码:

with rasterio.open("C:/Users/...raster.tif") as data:
    array = data.read()
  
    fig, ax = plt.subplots()
    ax.matshow(array, cmap='Greens')
    ax.axis('off')
    for (i, j), z in np.ndenumerate(array):
        ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center')

    fig = plt.gcf()
    plt.savefig("C:/Users/...grid.jpeg")
    plt.close(fig)

【问题讨论】:

    标签: python


    【解决方案1】:

    试试这样的:

    import matplotlib.pyplot as plt
    
    array = np.array([[[0.953, 0.938, 0.938],
    [0.959, 0.951, 0.944],
    [0.977, 0.976, 0.973]]])
    
    fig, ax = plt.subplots()
    ax.matshow(array, cmap='Greens')
    ax.axis('off')
    for (i, j), z in np.ndenumerate(array[0]):
        ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center')
    
    fig = plt.gcf()
    

    或压缩数组的第一个维度:array = array.squeeze(axis=0),然后在 for 循环中使用它。

    【讨论】:

    • 就是这样!我有一个 3d 数组,使用“array.squeeze(axis=0)”可以正常工作。谢谢:)
    【解决方案2】:

    正如您在链接的问题中看到的那样 Show the values in the grid using matplotlib 它给出了一个 2D 数组作为 grid 输入(开始和结束的两个括号):

    data = [['basis', 2007, 2008],
            [1, 2.2, 3.4],
            [2, 0, -2.2],
            [3, -4.1, -2.5],
            [4, -5.8, 1.2],
            [5, -5.4, -3.6],
            [6, 1.4, -5.9]]
    

    你的是 3 维(开头和结尾 3 个括号)并且语法格式错误,没有逗号分隔每个元素:

    [[[0.953 0.938 0.938]
    [0.959 0.951 0.944]
    [0.977 0.976 0.973]]]
    

    也许您可以立即调整输入或使用 NumPy 的 squeeze 将其转换为 suggested by Alone Together

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      相关资源
      最近更新 更多