使用matplotlib在Python中的直方图
作者:互联网
这个问题已经在这里有了答案: > Generating a PNG with matplotlib when DISPLAY is undefined 12个
我为此感到非常挣扎.有些事情我只是不明白.我有一个函数,我想用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
解决方法:
您会被状态机界面所困扰:
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?.
标签:python-2-7,matplotlib,graph,python,numpy 来源: https://codeday.me/bug/20191123/2066932.html