【问题标题】:Too Many Indices For Array when using matplotlib使用 matplotlib 时数组的索引过多
【发布时间】:2021-06-13 14:21:26
【问题描述】:

感谢您抽出宝贵时间阅读此问题。

我正在尝试在一行中绘制饼图。饼图的数量取决于返回的结果。

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(1,len(to_plot_arr))
labels = ['Label1','Label2','Label3','Label4']

pos = 0
for scope in to_plot_arr:
    if data["summary"][scope]["Count"] > 0:
       pie_data = np.array(db_data)
       axs[0,pos].pie(pie_data,labels=labels)
       axs[0,pos].set_title(scope)
        
    pos += 1

plt.show()

在代码中,db_data 看起来像:[12,75,46,29] 当我执行上面的代码时,我收到以下错误消息:

Exception has occurred: IndexError
too many indices for array: array is 1-dimensional, but 2 were indexed

我已尝试搜索可能导致此问题的原因,但找不到任何解决方案。我不确定“但 2 个已编入索引”是什么意思

我尝试使用以下方法生成饼图:

y = np.array(db_data)
plt.pie(y)
plt.show()

它会按预期生成饼图。所以,我不确定“数组的索引太多”是什么意思,哪个数组被引用以及如何解决这个问题。

希望你能帮我解决这个问题。

再次感谢您。

【问题讨论】:

  • 能否提供完整的追溯信息?或者至少是引发异常的确切行。谢谢

标签: python-3.x numpy matplotlib


【解决方案1】:

请注意,您在第 4 行创建的 axs 的形状为 (len(to_plot_arr),)1D 数组,但在第 11 行和第 12 行的循环中,您为其提供了 2 个索引,这告诉解释器它是2D 数组,并与其实际形状冲突。

这是一个修复:

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(1,len(to_plot_arr))
labels = ['Label1','Label2','Label3','Label4']

pos = 0
for scope in to_plot_arr:
    if data["summary"][scope]["Count"] > 0:
       pie_data = np.array(db_data)
       axs[pos].pie(pie_data,labels=labels)
       axs[pos].set_title(scope)
        
    pos += 1

plt.show()

干杯。

【讨论】:

  • 嗨迈克尔,感谢您抽出时间阅读我的问题并提供可能的解决方案。我不太明白我制作的 axs 是一维数组是什么意思,因为它被定义为“(1,len(to_plot_arr))”。因此,它应该是一个二维数组。我发现使用的是:“(2,len(to_plot_arr))”。当我使用它时,图表可以绘制。我将更详细地回答我的问题,说明我是如何解决这个问题的
【解决方案2】:

所以,我认为这不是技术上的答案,因为我仍然不知道是什么导致了错误,但我找到了一种方法来解决我的问题,同时仍然达到我想要的输出。

首先,当我改变时,我意识到: fig, axs = plt.subplots(1,len(to_plot_arr)) 到: fig, axs = plt.subplots(2,len(to_plot_arr)), 该图可以绘制。于是,我继续尝试其他变体,如(1,2),(2,1),(1,3),总是发现如果nrows`` or ncols```为1,就会出现错误。

幸运的是,对于我的用例,我需要的布局是 2 行,第一行为一列,跨越 2 行,底行为 2 列。

所以,(2,2) 非常适合我的用例。

然后我开始让顶行跨越 2 列,发现最好使用 Matplotlib 中的 GridSpec 来完成。在尝试弄清楚如何使用GridSpec 时,我了解到使用add_subplot() 会是一条更好的路线,并且更灵活。

所以,我的最终代码如下所示:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

def make_chart():
    fig = plt.figure()
    fig.set_figheight(8)
    fig.set_figwidth(10)

    # Gridspec is used to specify the grid distribution of the figure
    gs = GridSpec(2,len(to_plot_arr),figure=fig)

    # This allows for the first row to span all the columns
    r1 = fig.add_subplot(gs[0,:])

    tbl = plt.table(
        cellText = summary_data,
        rowLabels = to_plot_arr,
        colLabels = config["Key3"],
        loc ='upper left',
        cellLoc='center'
    )
    tbl.set_fontsize(20)
    tbl.scale(1,3)    


    r1.axis('off')
    
    pos = 0
    for scope in to_plot_arr:
        if data["Key1"][scope][0] > 0:
            pie_data = np.array(data["Key2"][scope])

            # Add a chart at the specified position
            r2 = fig.add_subplot(gs[1,pos])
            r2.pie(pie_data, autopct=make_autopct(pie_data))
            r2.set_title(config["Key3"][scope])
        
        pos += 1
    

    fig.suptitle(title, fontsize=24)
    plt.xticks([])
    plt.yticks([])
    fig.legend(labels,loc="center left",bbox_to_anchor=(0,0.25))   

    plt.savefig(savefile)

    return filename

这是我第一次尝试使用 Matplotlib,学习曲线很陡峭,但在一些患者和对文档的关注下,我能够完成我的任务。我确信有更好的方法来做我所做的事情。如果您确实知道更好的方法或知道如何解释我遇到的错误,请为此添加答案。

谢谢!

【讨论】:

    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2021-01-19
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多