使用pyplot时的数据处理

时间:2016-05-16 17:11:05

标签: python matplotlib

我遇到了问题,其中第一次如果用户想要绘制图表它工作正常,但如果再次选择相同的选项,我会看到如下错误。对我而言,pyplot持有的一些资源似乎没有被释放。如果是这样,我的理解是否正确,如何纠正?如果错了,可能会导致什么原因呢?

更多信息 - 只有当我尝试绘制图表时才会发生 - 如果我只是想显示数据,那就可以了。

代码:

default_options = {'0' : 'Below are the options',
                   '1' : '1 . Enter File path\'s for processing',
                   '2' : '2 . Display all categories',
                   '3' : '3 . Display type of forms',
                   '4' : '4 . Display for given form annual result',
                   '5' : '5 . Compare two form annual result ',
                   '6' : '6 . Compare two years annual result',
                   '99': '0 . Type 0 to exit '
                   }

labels = ["1st_quat", "2nd_quat", "3rd_quat", "4th_quat"]

def plotBarGraph(self, fiscal_year):
    index = np.arange(len(labels))
    bar_width = 0.1
    fig, ax = plt.subplots()
    appli_received = [data[0] for data in fiscal_year]
    appli_accepted = [data[1] for data in fiscal_year]
    appli_denied = [data[2] for data in fiscal_year]
    appli_pending = [data[3] for data in fiscal_year]

    plt.bar(index, appli_received, bar_width, alpha = 0.5, color='b')
    plt.bar(index + bar_width, appli_accepted,bar_width, alpha = 0.5, color='r')
    plt.bar(index + bar_width * 2, appli_denied, bar_width, alpha = 0.5, color='g')
    plt.bar(index + bar_width * 3,  appli_pending,bar_width, alpha = 0.5, color='k')
    plt.xticks(index, labels, rotation = 35)
    ax.tick_params(axis='both', which='major')
    plt.legend(['Received', 'Approved', 'Denied', 'Pending'], loc='upper left')
    plt.show()

def getUserInput(self):
    self.displayUserOption()
    user_input = int(raw_input())
    if self.validateUserInput(user_input):
        if user_input:
            self.processForAllFile(user_input)
            self.getUserInput()
    else:
        print " Please enter valid option \n "
        self.getUserInput() 

当用户再次尝试绘制图形时打印错误(我在选择再次绘制之前手动关闭绘图)

self.plotBarGraph(report)

    plt.bar(index, appli_received, bar_width, alpha = 0.5, color='b')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2089, in bar
    ret = ax.bar(left, height, width, bottom, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 4733, in bar
    nbars)
AssertionError: incompatible sizes: argument 'height' must be length 4 or scalar

1 个答案:

答案 0 :(得分:0)

看起来您labels变量(看起来是全局的)与fiscal_yearplotBarGraph的维度不匹配。变量index的维度取决于labels的长度。然后,您将fiscal_year展平为未知维度的列表,并尝试将它们用作具有len(labels)条的条形图的高度。

len(labels) != len(fiscal_year)时,matplotlib的高度太多或太少无法正确绘制条形图,这就是您看到错误的原因。