簡體   English   中英

如何在matplotlib中將變量名稱作為標題打印

[英]How to print variable name as a title in 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中無法輕松獲取變量的名稱(請參閱此答案 )。 傳遞給Python中的函數變量,也有使用哈克解決方案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()

但是,在您的情況下可能更整潔的另一種可能的解決方案是在函數中使用**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()

就個人而言,除了快速繪圖腳本之外,我還要定義一個你想要繪制的所有變量的字典,每個變量的名稱,並將其傳遞給函數。 這更明確,如果您將此繪圖用作更大代碼的一部分,則可確保您沒有任何問題...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM