Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 自动设置轴的标签_Python_Matplotlib - Fatal编程技术网

Python 自动设置轴的标签

Python 自动设置轴的标签,python,matplotlib,Python,Matplotlib,有没有办法根据代码中变量的名称自动设置绘图轴的标签。 例如: 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() 是否有任何方法向该代码中添加一些_函数,以使该示例的结果等效于: plt.xlabel('x_variable') plt.

有没有办法根据代码中变量的名称自动设置绘图轴的标签。 例如:

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()
是否有任何方法向该代码中添加一些_函数,以使该示例的结果等效于:

plt.xlabel('x_variable')
plt.ylabel('y_variable')

不是真的。但是,可以使用字典存储值,并使用键作为标签

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)
在您的例子中,x_变量和y_变量是numpy数组,因为您正在使用它们在matplotlib上绘图

因此,您可以根据需要使用以下函数来提取变量名并将其打印为标签

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))

您可能必须与本地人一起更改全局,但这取决于您如何在您的案例中使用它。

我认为这是一个坏主意。你可以通读其中的内容和评论。如前所述,这是不可靠的。它可能是,而且有更好的选择,如制作一本字典,列表,。。。但它可以解决问题,因为它意味着在y_变量=x_变量**1的情况下它将不起作用。