1

I have a series of variables that appear like this:

halpha = 6562.8
hbeta = 4861
ca1 =  8498
ca2 = 8542
ca3 =  8662
o3 = 5008.240

I have a plotting function here:

def abslines(molecule,title):
    plt.axvline(molecule, color = "r", label=title)
    plt.text(molecule-100, 40, title,rotation=90,fontsize=20)

And it works when input looks like:

abslines(he,"he")

And the function works just fine, but I don't want to have a ton of lines where I just call the function for each of the variables, so I put the variables in an array, and in a for loop I call the function. How do I call the variable name, which is the second input of the abslines function?

absarray = [halpha,hbeta,ca1,ca2,ca3,o3,na,mg,he]
for i in absarray:
    abslines(i,"i")
3

4 Answers 4

2

There are ways to inspect the script's variable name but that seems to be over kill here since you can construct a dictionary with it's name and the "function" and just call it. Use the key for the name you want, and the value to be the function:

absarray = {"halpha":halpha,"hbeta":hbeta,"ca1":ca1,"ca2":ca2,"ca3":ca3,"o3":o3,"na":na,"mg":mg,"he":he}

for k,v in absarray.items():
    abslines(v,k)
Sign up to request clarification or add additional context in comments.

Comments

1

If instead of variables you use a dictionary, you can simply index the dictionary with the name of each item. Like:

abs = {
    # optional init - may or may not be useful:
    "halpha": 0,
    "hbeta": 0,
    ...
}
...
abs["halpha"] = ...
...
for name in abs:
    abslines(abs[name], name)

Comments

0

Use a dict, skip the variables that just hold what - molecule weights?

from  matplotlib import pyplot as plt

data = { "halpha" : 6562.8, "hbeta" : 4861,   "ca1" :  8498,
         "ca2"    : 8542,   "ca3"   :  8662,  "o3"  : 5008.240,  }

def abslines(molecule,title):
    plt.axvline(molecule, color = "r", label=title)
    plt.text(molecule-100, 0.40, title,rotation=90,fontsize=20) # fix  y

for b,a in data.items():
    abslines(a,b)

plt.show()

to get

pic

Comments

0

Easiest may be to use python's built-in map() function:

>>> map(lambda n: abslines(n, 'i'), absarray)

(6562.8, 'i')
(4861, 'i')
(8498, 'i')
(8542, 'i')
(8662, 'i')
(5008.24, 'i')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.