如何在matplotlib中将变量名称作为标题打印

时间:2015-09-29 10:58:33

标签: python 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...")

目前,我能想到的唯一解决方案是制作我的变量字典,我想避免。非常感谢任何和所有的帮助。

1 个答案:

答案 0 :(得分:1)

在python中无法轻松获取变量的名称(请参阅此answer)。对于传递给python中的函数的变量,有使用inspect的hacky解决方案,详细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然后在命令行上定义的变量名将是打印的,例如,< / p>

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

就个人而言,除了快速绘图脚本之外,我还要定义一个您想要绘制的所有变量的字典,并为每个变量添加名称,并将其传递给函数。这更明确,如果您将此绘图用作更大代码的一部分,则可确保您没有任何问题...