plt.title上的索引超出范围



我正在准备一个程序,以便在参数中提供一个json格式的文件,该文件读取参数以填充绘图。我正在使用matplotlib。

如果我输入代码plt.title("Test title"),一切都很顺利

如果我放

文件中的{ "title": "Test title" },并在程序中设置路径(不在参数中(,将之前的替换为plt.title(json_file["title"]),一切顺利。

但是,如果我放入参数,调用-f path/to/json,即使json文件加载正确,当调用行plt.title(json_file["title"])时,也会引发索引超出范围的错误。我不明白为什么,因为我没有经过任何数组。

我已经在stackoverflow中进行了搜索,并在title的文档中进行了尝试,但它没有报告它会引发这个错误。

我正在做的一件事是用yaml读取json文件,因为用json我收到了unicode中的所有内容,并且出现了相同的错误,所以我尝试了不同的方法。

以下代码稍微简单一点,但再现了错误:

import matplotlib.pyplot as plt
import json
import yaml
import sys
def configure(json_file):
title = json_file["title"]
plt.title(title)
def handleArguments():
arguments = sys.argv
# The first item is removed because it's the filename
arguments.pop(0)
file = None
while(len(arguments) > 0):
argument = arguments[0]
if(argument == "-f"):
file = arguments[1]
arguments.pop(0)
arguments.pop(0)
else:
raise Exception('Argument not found: {}'.format(argument))
return (file)
(file) = handleArguments()
# file = "data_feed/test.json"
f = open(file,)
# Reading with yaml because json.load reads as unicode, not strings
json_file = yaml.safe_load(f)
configure(json_file)
x = [1, 2, 3]
y = [2, 5, 8]
plt.plot(x, y)  
plt.show()

以下是要求的追溯:

Traceback (most recent call last):
File "delete_me.py", line 31, in <module>
configure(json_file)
File "delete_me.py", line 8, in configure
plt.title(title)
File "/home/silkking/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 1419, in title
return gca().set_title(s, *args, **kwargs)
File "/home/silkking/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 969, in gca
return gcf().gca(**kwargs)
File "/home/silkking/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 586, in gcf
return figure()
File "/home/silkking/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 533, in figure
**kwargs)
File "/home/silkking/.local/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 161, in new_figure_manager
return cls.new_figure_manager_given_figure(num, fig)
File "/home/silkking/.local/lib/python2.7/site-packages/matplotlib/backends/_backend_tk.py", line 1046, in new_figure_manager_given_figure
window = Tk.Tk(className="matplotlib")
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1823, in __init__
baseName = os.path.basename(sys.argv[0])
IndexError: list index out of range

出于某种原因,我不明白,用python2运行它会出错,但用python3运行它没问题。

最新更新