我的目标是创建一个简单的函数,为带有已绘制变量名称的图形添加标题。
到目前为止,我有:
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));
Run Code Online (Sandbox Code Playgroud)
在哪里:
plt.title("%s customers with filter less/greater...")
Run Code Online (Sandbox Code Playgroud)
我很乐意说:
plt.title("%s customers with %s less/greater...")
Run Code Online (Sandbox Code Playgroud)
目前,我能想到的唯一解决方案是为我的变量制作一个字典,这是我想避免的。任何帮助都将不胜感激。
在 python 中不可能轻松获取变量的名称(请参阅此答案)。对于传递给 python 中的函数的变量,有一些使用的 hacky 解决方案inspect,此处详细介绍了基于此答案的针对您的案例的解决方案,
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()
Run Code Online (Sandbox Code Playgroud)
但是,另一种可能的解决方案(在您的情况下可能更简洁)是在您的函数中使用**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()
Run Code Online (Sandbox Code Playgroud)
就个人而言,对于除快速绘图脚本之外的任何内容,我都会定义一个包含您想要绘制的所有变量的字典,并为每个变量指定名称,并将其传递到函数中。这是更明确的,并且确保如果您使用此绘图作为更大代码的一部分不会出现任何问题......