我的目标是创建一个简单的函数,使用已绘制的变量的名称来标题图形.
到目前为止,我有:
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...")
目前,我能想到的唯一解决方案是编写我的变量字典,我想避免.非常感谢任何和所有的帮助.
解决方法:
在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然后在命令行上定义的变量名将是打印的,例如,
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()
就个人而言,除了快速绘图脚本之外,我还要定义一个你想要绘制的所有变量的字典,每个变量的名称,并将其传递给函数.这更明确,如果您将此绘图用作更大代码的一部分,则可确保您没有任何问题…
标签:python,matplotlib