Reputation: 837
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')
Upvotes: 0
Views: 670
Reputation: 1307
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.
Upvotes: 1
Reputation: 36598
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)
Upvotes: 1