【问题标题】:Histogram in Python Using matplotlib [duplicate]Python中的直方图使用matplotlib [重复]
【发布时间】:2013-04-27 02:02:21
【问题描述】:

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

【问题讨论】:

  • 你需要解释一下“不起作用”是什么意思。您认为“不工作”的原因是什么?如果出现错误,错误信息是什么?
  • 当您尝试运行此类程序时,通常会收到一条错误消息。错误信息是什么?如果您添加此内容,那么我们可能会提供帮助
  • @BrenBarn 这是使用matplotlib 的状态机接口的问题。它会默默地做“错误”的事情,因为这是完全有效和正确(但不是功能性)的代码。
  • 您应该使用非交互式后端之一(因为您似乎没有运行 X 服务器)

标签: python graph python-2.7 numpy matplotlib


【解决方案1】:

你被状态机界面吓到了:

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?

【讨论】:

  • 我更新了您的代码,但我仍然收到此错误:文件“/usr/lib/pymodules/python2.7/matplotlib/pyplot.py”,第 343 行,在图 **kwargs ) 文件“/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py”,第 80 行,在 new_figure_manager 窗口 = Tk.Tk() 文件“/usr/lib/python2.7/lib-tk/ Tkinter.py",第 1688 行,在 init 中 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) TclError: no display name and no $DISPLAY环境变量
  • @user2236076:听起来您的后端设置不正确。您可能想就此提出一个单独的问题。
猜你喜欢
  • 2012-07-12
  • 2015-09-19
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 2014-04-15
  • 1970-01-01
  • 2020-05-20
相关资源
最近更新 更多