我正在努力解决这个问题。还有一些我没有得到的东西。我有一个函数,我想绘制一个字典的直方图,其中x轴上的键和y轴上的值,然后将文件保存在调用函数时指定的位置。我所拥有的是:
import matplotlib.pyplot as plt
def test(filename):
dictionary = {0:1000, 1:20, 2:15, 3:0, 4:5}
xmax = max(dictionary.keys())
ymax = max(dictionary.values())
plt.hist(dictionary,xmax)
plt.title('Histogram Title')
plt.xlabel('Label')
plt.ylabel('Another Label')
plt.axis([0, xmax, 0, ymax])
plt.figure()
plt.savefig(filename)
test('test_graph.svg')
我根本无法让这个工作,我很长时间都在努力阅读其他问题和文档。任何帮助将不胜感激。感谢。
编辑:
我遇到的错误是:
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 343, in figure
**kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1688, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
TclError: no display name and no $DISPLAY environment variable
答案 0 :(得分:3)
您正被状态机界面咆哮:
import matplotlib.pyplot as plt
def test(filename):
dictionary = {0:1000, 1:20, 2:15, 3:0, 4:5}
xmax = max(dictionary.keys())
ymax = max(dictionary.values())
plt.figure() # <- makes a new figure and sets it active (add this)
plt.hist(dictionary,xmax) # <- finds the current active axes/figure and plots to it
plt.title('Histogram Title')
plt.xlabel('Label')
plt.ylabel('Another Label')
plt.axis([0, xmax, 0, ymax])
# plt.figure() # <- makes new figure and makes it active (remove this)
plt.savefig(filename) # <- saves the currently active figure (which is empty in your code)
test('test_graph.svg')
有关matplotlib的状态机与OO接口的更长解释,请参阅How can I attach a pyplot function to a figure instance?。