0

Is there any way to set the labels of a plot's axis automatically according to the name that the variables have in the code. For example:

import matplotlib.pyplot as plt    
import numpy as np
x_variable=np.linspace(1,5)
y_variable=x_variable**2
plt.plot(x_variable,y_variable)
some_function()

is there any way to add some_function() to this code such that the result for this example will be equivalent to:

plt.xlabel('x_variable')
plt.ylabel('y_variable')
Numlet
  • 819
  • 1
  • 9
  • 21
  • 1
    I think this is general a bad idea. You can read through [this question](https://stackoverflow.com/questions/2553354/how-to-get-a-variable-name-as-a-string) and comments therein. – ImportanceOfBeingErnest May 04 '18 at 12:34

2 Answers2

1

In your case x_variable and y_variable are numpy arrays as you are using them to plot on matplotlib.

So you can use the following function as you requested to extract the variable name and plot it as a label

import matplotlib.pyplot as plt    
import numpy as np

def Return_variable_name_as_string(myVar):
    return [ k for k,v in globals().iteritems() if np.array_equal(v,myVar)][0]

x_variable=np.linspace(1,5)
y_variable=x_variable**2
plt.plot(x_variable,y_variable)
plt.xlabel(Return_variable_name_as_string(x_variable))
plt.ylabel(Return_variable_name_as_string(y_variable))

You may have to change globals with locals, but that will depend on how you use it on your case.

iblasi
  • 1,269
  • 9
  • 21
0

Not really. However, you can use a dictionary to store the values and use the keys as the labels.

import matplotlib.pyplot as plt    
import numpy as np
data = {}
x = 'x_variable'
y = 'y_variable'
data[x] = np.linspace(1,5)
data[y] = x_variable**2
plt.plot(data[x], data[y])

plt.xlabel(x)
plt.ylabel(y)
James
  • 32,991
  • 4
  • 47
  • 70