使用pyplot进行数据处理

问题描述:

我遇到了问题,其中第一次如果用户想要绘制图形,它可以正常工作,但如果再次选择相同的选项,则会看到如下所示的错误。对我来说,似乎pyplot所持有的一些资源没有得到释放。我的理解是否正确?如何解决?如果错了会是什么原因呢?使用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 
+0

为了理解发生了什么,看起来我们需要看到'plotBarGraph'的代码 – mobiusklein

+0

@mobiusklein - 我已经更新了代码请求的问题 – oneday

它看起来像你可能有显示为全局的labels变量和的尺寸plotBarGraph之间不匹配。变量index的尺寸取决于labels的长度。然后,将fiscal_year平铺为未知尺寸的列表,并尝试将它们用作条形图的高度,精确到len(labels)

len(labels) != len(fiscal_year)时,matplotlib的高度太多或太少,无法正确绘制条形图,这就是为什么你会看到你所看到的错误。

+0

正如我所说的它第一次工作 - 只有当我选择再次选项它不起作用并抛出错误。正如你从我的代码中可以看到的那样,用户可以多次选择相同的选项,所以第一次情况很好,第二次出现错误 – oneday

+0

你能否确认'labels'的值是否与' fiscal_year'? “标签”的价值如何确定? – mobiusklein

+0

我已更新标签值 - 是它的全局变量。很抱歉,我无法理解它是否能够第一次工作,为什么映射必须第二次做任何事情 - 没有数据发生变化,只有第二次发送相同的请求。理解你的观点会很棒 – oneday