Matplotlib变量问题

时间:2016-04-01 05:04:27

标签: python numpy matplotlib

我几乎是全新的Python和matplotlib,所以我们一直在努力调整Python文档中的一个示例来获取我需要完成的图形。但是,我为rect1rect2调用以及ax.text中的ax获取了未定义的名称错误。我有一种感觉,它与不跨函数定义传递的值有关,但我无法弄清楚正确的语法。有什么想法吗?

P.S。如有必要,我可以提供更多信息;这是我的第一篇文章。

from inventoryClass import stockItem

import numpy as np
import matplotlib.pyplot as plt

def plotInventory(itemRecords):

    stockBegin = []
    stockFinish = []    
    stockID = []    
    stockItems = []
    for rec in itemRecords.values() :
        stockBegin.append(rec.getStockStart)
        stockFinish.append(rec.getStockOnHand)
        stockID.append(rec.getID)
        stockItems.append(rec.getName)
    N = len(stockBegin)    


ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, stockBegin, width, color='r')
rects2 = ax.bar(ind + width, stockFinish, width, color='y')

# add some text for labels, title and axes ticks
ax.set_ylabel('Inventory')
ax.set_title('Stock start and end inventory, by item')
ax.set_xticks(ind + width)
ax.set_xticklabels((str(stockID[0]), str(stockID[1]), str(stockID[1])))

ax.legend((rects1[0], rects2[0]), ('Start', 'End'))

def autolabel(rects) :

    for rect in rects :
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
            '%d' % int(height),
            ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

1 个答案:

答案 0 :(得分:0)

变量rects1和rects2仅存在于plotInventory的范围内,因此python不知道你所引用的是什么' rects1'。有两种方法可以解决这个问题:

  1. 您可以返回值,以便它们在全局范围内可用:

    def plotInventory(itemRecords):
        # ... code ... #
        return rects1, rects2
    
    rects1, rects2 = plotInventory(records)
    autolabel(rects1)
    autolabel(rects2)
    
    plt.show()
    
  2. 你可以从plotInventory里面调用autolabel:

    def plotInventory(itemRecords):
        # ... code ... #
        autolabel(rects1)
        autolabel(rects2)
    
  3. 至于ax,你有同样的问题和相同的解决方案,除了你需要将ax传递给autolabel,例如:

    def autolabel(ax, rects):
        # ... code ... #
    
    ax, rects1, rects2 = plotInventory(records)
    autolabel(ax, rects1)
    autolabel(ax, rects2)
    

    还记得从plotInventory返回ax!