python输出变量的名字_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...")

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

解决方法:

在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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值