使用拆分列表条目作为参数时出现 matplotlib 错误
matplotlib error when using split list entry as argument
我想在matplotlib中使用由外观命令组成的列表条目,方便编辑线条颜色和类型。但是当我 运行 以下代码时,我得到 2 个错误:
- '类型对象获得了关键字参数的多个值'ax''
Traceback (most recent call last):
File "./plotMeltFront.py", line 34, in <module>
data.plot(0, 1, ax=ax1, label=myLabel, *sets[i][2].split())
File "/home/ksalscheider/.local/lib/python3.6/site-packages/pandas/plotting/_core.py", line 872, in __call__
plot_backend.__name__, self._parent, args, kwargs
File "/home/ksalscheider/.local/lib/python3.6/site-packages/pandas/plotting/_core.py", line 859, in _get_call_args
kwargs = dict(arg_def, **pos_args, **kwargs)
TypeError: type object got multiple values for keyword argument 'ax'
- 在删除 ax 参数时,错误显示 'color="C0" is not a valid plot kind'
Traceback (most recent call last):
File "./plotMeltFront.py", line 34, in <module>
data.plot(0, 1, label=myLabel, *sets[i][2].split())
File "/home/ksalscheider/.local/lib/python3.6/site-packages/pandas/plotting/_core.py", line 882, in __call__
raise ValueError(f"{kind} is not a valid plot kind")
ValueError: color="C0" is not a valid plot kind
我一个都不明白。对于 1 我没有在列表中声明第二个 ax 值,为什么这么说?写入 data.plot(0, 1, label=myLabel, 'color="C0"')
时也会出现错误 2(注意 ' 周围的颜色)。这模仿列表条目的外观,打印列表。有没有办法从拆分列表条目中删除 '?
我在 link python script with example data
中包含了带有几个示例集的脚本
#!/usr/bin/python3
import os
import matplotlib.pyplot as plt
import pandas as pd
sets = []
iOld = -1
#--------USER EDIT--------#
#["set directory name", "label", 'set appearence']
sets.append(["set1", "Experiment", 'color="C0" linestyle=":"'])
sets.append(["set2", "Linear", 'color="C1" linestyle="--"'])
sets.append(["set3", "Erf", 'color="C2" linestyle="-."'])
print(sets[0][2].split())
#------USER EDIT END------'
fig = plt.figure()
ax1 = fig.add_subplot()
for i in range(len(sets)):
for j in os.listdir(sets[i][0]):
filepath = os.path.abspath(sets[i][0]) + "/" + j
data = pd.read_csv(filepath, delimiter=',', engine='python',
header=None, skipfooter=1, error_bad_lines=False)
if i != iOld:
myLabel = sets[i][1];
else:
myLabel = '_nolegend_'
data.plot(0, 1, ax=ax1, label=myLabel, *sets[i][2].split())
iOld = i
plt.show()
PS:“nolegend”条目会引发很多警告,有没有办法禁用它们?
要为函数提供额外参数,您不能使用拆分字符串。在问题示例中,拆分字符串将显示为:
# data.plot(0, 1, ax=ax1, label=myLabel, *sets[i][2].split())
data.plot(0, 1, ax=ax1, label=myLabel, 'color="C0"', 'linestyle=":"')
这是无效的 Python 代码。 Python 不会将其解释为 parametername=value
而只是一个字符串。由于 pandas 对参数进行了一些重新排列,因此生成了一条无用的错误消息(似乎将其解释为 ax='color="C0"'
)。
方法是将这些值存储在字典中,可以通过 **
:
将其转换为 parameter=value
对
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
sets = []
sets.append(["set1", "Experiment", {"color": "C0", "linestyle": ":"}])
sets.append(["set2", "Linear", {"color": "C1", "linestyle": "--"}])
sets.append(["set3", "Erf", {"color": "C2", "linestyle": "-."}])
fig = plt.figure()
ax1 = fig.add_subplot()
iOld = None
for i in range(len(sets)):
for j in range(2):
data = pd.DataFrame({'x': np.arange(100), 'y': np.random.randn(100).cumsum()})
myLabel = sets[i][1] if i != iOld else '_nolegend_'
legend_dict = {'legend': i != iOld}
data.plot(0, 1, ax=ax1, label=myLabel, **sets[i][2], **legend_dict)
iOld = i
plt.show()
有关 _nolegend_
的烦人警告是 pandas 如何调用 matplotlib 图例函数的结果。在这种情况下,一种方法是为不应出现在图例中的图添加 legend=False
。
我想在matplotlib中使用由外观命令组成的列表条目,方便编辑线条颜色和类型。但是当我 运行 以下代码时,我得到 2 个错误:
- '类型对象获得了关键字参数的多个值'ax''
Traceback (most recent call last):
File "./plotMeltFront.py", line 34, in <module>
data.plot(0, 1, ax=ax1, label=myLabel, *sets[i][2].split())
File "/home/ksalscheider/.local/lib/python3.6/site-packages/pandas/plotting/_core.py", line 872, in __call__
plot_backend.__name__, self._parent, args, kwargs
File "/home/ksalscheider/.local/lib/python3.6/site-packages/pandas/plotting/_core.py", line 859, in _get_call_args
kwargs = dict(arg_def, **pos_args, **kwargs)
TypeError: type object got multiple values for keyword argument 'ax'
- 在删除 ax 参数时,错误显示 'color="C0" is not a valid plot kind'
Traceback (most recent call last):
File "./plotMeltFront.py", line 34, in <module>
data.plot(0, 1, label=myLabel, *sets[i][2].split())
File "/home/ksalscheider/.local/lib/python3.6/site-packages/pandas/plotting/_core.py", line 882, in __call__
raise ValueError(f"{kind} is not a valid plot kind")
ValueError: color="C0" is not a valid plot kind
我一个都不明白。对于 1 我没有在列表中声明第二个 ax 值,为什么这么说?写入 data.plot(0, 1, label=myLabel, 'color="C0"')
时也会出现错误 2(注意 ' 周围的颜色)。这模仿列表条目的外观,打印列表。有没有办法从拆分列表条目中删除 '?
我在 link python script with example data
中包含了带有几个示例集的脚本#!/usr/bin/python3
import os
import matplotlib.pyplot as plt
import pandas as pd
sets = []
iOld = -1
#--------USER EDIT--------#
#["set directory name", "label", 'set appearence']
sets.append(["set1", "Experiment", 'color="C0" linestyle=":"'])
sets.append(["set2", "Linear", 'color="C1" linestyle="--"'])
sets.append(["set3", "Erf", 'color="C2" linestyle="-."'])
print(sets[0][2].split())
#------USER EDIT END------'
fig = plt.figure()
ax1 = fig.add_subplot()
for i in range(len(sets)):
for j in os.listdir(sets[i][0]):
filepath = os.path.abspath(sets[i][0]) + "/" + j
data = pd.read_csv(filepath, delimiter=',', engine='python',
header=None, skipfooter=1, error_bad_lines=False)
if i != iOld:
myLabel = sets[i][1];
else:
myLabel = '_nolegend_'
data.plot(0, 1, ax=ax1, label=myLabel, *sets[i][2].split())
iOld = i
plt.show()
PS:“nolegend”条目会引发很多警告,有没有办法禁用它们?
要为函数提供额外参数,您不能使用拆分字符串。在问题示例中,拆分字符串将显示为:
# data.plot(0, 1, ax=ax1, label=myLabel, *sets[i][2].split())
data.plot(0, 1, ax=ax1, label=myLabel, 'color="C0"', 'linestyle=":"')
这是无效的 Python 代码。 Python 不会将其解释为 parametername=value
而只是一个字符串。由于 pandas 对参数进行了一些重新排列,因此生成了一条无用的错误消息(似乎将其解释为 ax='color="C0"'
)。
方法是将这些值存储在字典中,可以通过 **
:
parameter=value
对
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
sets = []
sets.append(["set1", "Experiment", {"color": "C0", "linestyle": ":"}])
sets.append(["set2", "Linear", {"color": "C1", "linestyle": "--"}])
sets.append(["set3", "Erf", {"color": "C2", "linestyle": "-."}])
fig = plt.figure()
ax1 = fig.add_subplot()
iOld = None
for i in range(len(sets)):
for j in range(2):
data = pd.DataFrame({'x': np.arange(100), 'y': np.random.randn(100).cumsum()})
myLabel = sets[i][1] if i != iOld else '_nolegend_'
legend_dict = {'legend': i != iOld}
data.plot(0, 1, ax=ax1, label=myLabel, **sets[i][2], **legend_dict)
iOld = i
plt.show()
有关 _nolegend_
的烦人警告是 pandas 如何调用 matplotlib 图例函数的结果。在这种情况下,一种方法是为不应出现在图例中的图添加 legend=False
。