我用以下函数调用函数load():
load(r'M:\test_3.p', marker = '*', linestyle = '-.', color = 'b', grid = True)
在该函数中,我正在打印kwargs [' color']并且我只得到一个值,我得到值b(我最初在函数调用中输入的值)。我还有其他原因会收到此错误吗?在脚本的最末端的exec(plotting_string)行中出现错误。有人可以帮忙吗?
错误具体是:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "functions_mar.py", line 236, in load
exec(plotting_string)
File "<string>", line 1, in <module>
TypeError: plot() got multiple values for keyword argument 'color'
以下代码:
def load(string, **kwargs):
#Unpickling the data in order
f = open(string, 'r')
raw_data = pk.load(f)
title = pk.load(f)
xlabel = pk.load(f)
ylabel = pk.load(f)
line_labels = pk.load(f)
line_colors = pk.load(f)
line_marker = pk.load(f)
f.close()
#Specifying the graph
fig0 = plt.figure()
ax = fig0.add_subplot(1,1,1)
plt.ion()
# Handles plt. methods (included some basic ones but in future will add library of all)
if kwargs.get('title') is not None:
plt.title(kwargs['title'])
del kwargs['title']
else:
plt.title(title)
if kwargs.get('xlabel') is not None:
plt.xlabel(kwargs['xlabel'])
del kwargs['xlabel']
else:
plt.xlabel(xlabel)
if kwargs.get('ylabel') is not None:
plt.ylabel(kwargs['ylabel'])
del kwargs['ylabel']
else:
plt.ylabel(ylabel)
if kwargs.get('grid') is not None:
try:
plt.grid(kwargs['grid'])
del kwargs['grid']
except Exception as e:
plt.grid(True)
del kwargs['grid']
print 'Error: ',e, '\n ERROR: Grid can only be BOOLEAN: True or False.'
else:
plt.grid(True)
#VARIABLE ARGUMENT HANDLER
# Handles variable keyword arguments as to not coincide with the defaults
if kwargs is not None:
plotting_string ='ax.plot(x,y, label = line_labels[i], color = line_colors[i], marker = line_marker, **kwargs)'
if kwargs.get('marker') is not None:
plotting_string = plotting_string.replace('line_marker', '\''+ kwargs['marker'] +'\'' )
del kwargs['marker']
if kwargs.get('color') is not None:
if len(kwargs['color']) != len(raw_data):
if len(kwargs['color']) == 1:
try:
plotting_string = plotting_string.replace('line_colors[i]', '\'' + kwargs['color']+'\'' )
except:
print 'Color must be a string!!'
else:
print 'Must enter as many colors as there are lines'
del kwargs['color']
else:
colors = kwargs['color']
plotting_string = plotting_string.replace('line_colors', 'colors')
del kwargs['color']
#Regenerating the plot from the unpickled data
print kwargs['color']
for i,line in enumerate(raw_data):
x = line[0]
y = line[1]
if kwargs is not None:
exec(plotting_string)
else: # User didnt enter any additional arguments
ax.plot(x,y, label = line_labels[i], color = line_colors[i], marker = line_marker, **kwargs)
plt.legend()
plt.show()