3

我正在为此苦苦挣扎。有些东西我只是没有得到。我有一个函数,我想用 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
4

1 回答 1

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')

请参阅如何将 pyplot 函数附加到图形实例?有关 matplotlib 的状态机与 OO 接口的详细说明。

于 2013-05-02T19:16:22.163 回答