0

I need to save the output of the function to a file with a name of the variable passed to that function. I have tried using a function from a stackoverflow user.

def var_name(**variables):
    return [x for x in variables]

My code as follows,
dist is numpy array dataset containing different arrays.

MTnum=10
import matplotlib.pyplot as plt
import numpy as np
def Plot(dist, sav=False):
    MT_dat = np.vsplit(dist,MTnum)
    for i,mtdat in enumerate(MT_dat):
        plt.figure(i)
        for j in range(len(mtdat[0])-1):
            plt.plot(MT_dat[i][:,0],MT_dat[i][:,j+1])
        plt.xlabel('time')
        plt.ylabel('distance')
        plt.title('MT_'+str(i+1)+var_name(dist=dist)+'.png')
        if sav == True:
            plt.savefig('MT_'+str(i+1)+var_name(dist=dist)+'.png')
        plt.show()

If I use function Plot(set1) ,files are saved with "dist" suffix instead of "set1". Please suggest a proper way of doing it.

Yash
  • 1
  • 2

2 Answers2

0

There's no proper way to do it. The dist parameter of Plot() is just a name that will be assigned to value that was given as its first argument, which might not be a variable at all—for example it might be the literal string "foobar" or whatever a function call returned that was used as the argument in the call. Since you presumably know what the argument's name is, assuming it has one, just pass it explictly as the dist parameter.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • i wanted a function since i want to pass multiple data-sets, so manual entry is not a good option. – Yash Oct 06 '17 at 08:35
  • At the place(s) you call `Plot()` in your code, you know the name of the variable being passed to it, so it would seem to follow that you would also be able to save the output of the function to a file with that name. If there's more than one somehow, then save them in a `list`. – martineau Oct 06 '17 at 15:42
  • In simple terms, modify `Plot()` so it takes a value _and_ a variable name—i.e. `Plot(dist, varname, sav=False):`—then call it like `Plot(set1, 'set1')`, `Plot(set2, 'set2')`, `Plot(10, 'no name')`, etc. – martineau Oct 06 '17 at 15:54
0

Your function var_name will return names of dict in variables, not numpy array. What structure is your dataset dist? Try changing the function definition var_name(**variables) to var_name(*variables) (single asterisk). Then change the function call to var_name(dist).

Alex
  • 1