2016-04-01 12 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の範囲内に存在するので、Pythonは、あなたが「rects1」でに言及しているものを知っていません。これを修正するには、2つの可能な方法があります。

  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) 
    

、あなたは同じ広報を持っていますあなたが例えば、AUTOLABELに斧を渡す必要があることを除いてoblemと同じソリューション、:

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

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

は、同様にplotInventoryから斧を返すことを忘れないでください!

+0

本当に助けてくれてありがとうございました。乾杯! –