2015-09-29 89 views
3

我的目標是創建一個簡單的函數,該函數使用已繪製的變量的名稱標題圖形。如何在matplotlib中打印變量名稱作爲標題

到目前爲止,我有:

def comparigraphside(rawvariable, filtervariable, cut): 
    variable = rawvariable[filtervariable > 0] 
    upperbound = np.mean(variable) + 3*np.std(variable) 
    plt.figure(figsize=(20,5)) 
    plt.subplot(121) 
    plt.hist(variable[filtervariable <= cut], bins=20, range=(0,upperbound), normed=True) 
    plt.title("%s customers with filter less than or equal to %s" % (len(variable[filtervariable <= cut]), cut)) 
    plt.subplot(122) 
    plt.hist(variable[filtervariable > cut], bins=20, range=(0,upperbound), normed=True) 
    plt.title("%s customers with filter greater than %s" % (len(variable[filtervariable > cut]), cut)); 

而且它是:

plt.title("%s customers with filter less/greater...") 

我喜歡它說:

plt.title("%s customers with %s less/greater...") 

目前唯一的解決辦法,我可以想想涉及製作我想要避免的變量字典。任何和所有的援助非常感謝。

+0

相關:http://stackoverflow.com/questions/2553354/how-to-get-a-variable -name作爲一種串式的Python – cel

回答

1

在python中不容易獲取變量的名稱(請參閱此answer)。傳遞給Python中的函數變量,也有使用inspect哈克解決方案,詳細介紹here基於此answer爲你的情況的解決方案,

import matplotlib.pyplot as plt 
import numpy as np 
import inspect 
import re 

def comparigraphside(rawvariable, filtervariable, cut): 

    calling_frame_record = inspect.stack()[1] 
    frame = inspect.getframeinfo(calling_frame_record[0]) 
    m = re.search("comparigraphside\((.+)\)", frame.code_context[0]) 
    if m: 
     rawvariablename = m.group(1).split(',')[0] 

    variable = rawvariable[filtervariable > 0] 
    filtervariable = filtervariable[filtervariable > 0] 
    upperbound = np.mean(variable) + 3*np.std(variable) 
    plt.figure(figsize=(20,5)) 
    plt.subplot(121) 
    plt.hist(variable[filtervariable <= cut], bins=20, range=(0,upperbound), normed=True) 
    title = "%s customers with %s less than or equal to %s" % (len(variable[filtervariable <= cut]), rawvariablename, cut) 
    plt.title(title) 
    plt.subplot(122) 
    plt.hist(variable[filtervariable > cut], bins=20, range=(0,upperbound), normed=True) 
    plt.title("%s customers with %s greater than %s" % (len(variable[filtervariable > cut]), rawvariablename, cut)); 


#A solution using inspect 
normdist = np.random.randn(1000) 
randdist = np.random.rand(1000) 

comparigraphside(normdist, normdist, 0.7) 
plt.show() 

comparigraphside(randdist, normdist, 0.7) 
plt.show() 

然而,另一種可能的solution,這可能是整潔,你的情況是在你的函數中使用**kwargs,然後將打印在命令行中定義的變量名是什麼,例如,

import matplotlib.pyplot as plt 
import numpy as np 

normdist = np.random.randn(1000) 
randdist = np.random.rand(1000) 

#Another solution using kwargs 
def print_fns(**kwargs): 
    for name, value in kwargs.items(): 
     plt.hist(value) 
     plt.title(name) 

print_fns(normal_distribution=normdist) 
plt.show() 

print_fns(random_distribution=randdist) 
plt.show() 

個人,比快速繪製腳本等什麼,我會定義所有的字典你想要的變量o繪製每個圖的名稱,並將其傳遞給函數。這是更明確的,並確保您沒有任何問題,如果您使用此繪圖作爲更大的代碼的一部分...