2016-04-01 48 views
0

我幾乎是全新的Python和matplotlib,所以一直在努力使Python文檔中的示例適合我需要完成的圖形。但是,我得到rect1rect2調用的未定義名稱錯誤,以及ax.text中的ax。我有一種感覺,它與不通過函數定義傳遞的值有關,但我無法弄清楚正確的語法。有任何想法嗎?Matplotlib變量問題

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() 

回答

0

變量rects1和rects2只存在於plotInventory的範圍等蟒蛇不知道你被「rects1」指的是什麼。有兩種可能的方法來解決這個問題:

  1. 您可以回報數值,以便他們在全球範圍內都有效:

    def plotInventory(itemRecords): 
        # ... code ... # 
        return rects1, rects2 
    
    rects1, rects2 = plotInventory(records) 
    autolabel(rects1) 
    autolabel(rects2) 
    
    plt.show() 
    
  2. 您只需撥打自動標籤從內plotInventory:

    def plotInventory(itemRecords): 
        # ... code ... # 
        autolabel(rects1) 
        autolabel(rects2) 
    

至於斧,你有相同的PR除了你需要將ax傳入autolabel之外,例如:

def autolabel(ax, rects): 
    # ... code ... # 

ax, rects1, rects2 = plotInventory(records) 
autolabel(ax, rects1) 
autolabel(ax, rects2) 

記得還要從plotInventory返回ax!

+0

感謝您的幫助,這確實解決了我的問題。乾杯! –