【问题标题】:plt.show() not working in spyder ideplt.show() 在 spyder ide 中不起作用
【发布时间】:2018-01-22 15:04:44
【问题描述】:

我是 Python 和 Spyder 的新手。我正在使用 Python 2.7.13 和 Spyder 3.1.4。我无法让plt.show() 处理我的数据,也无法从网站上重现简单的直方图示例。 plt.draw() 也不起作用。我已将图形后端从内联更改为自动到 Qt4 到 Qt5,就像提出的类似问题一样,但这些都不起作用。如果在 IPython 控制台中键入 fig,它将显示图形。我在这里发布示例。任何有关如何解决此问题的建议表示赞赏。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

fig = plt.figure()
ax = fig.add_subplot(111)

# the histogram of the data
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)

# hist uses np.histogram under the hood to create 'n' and 'bins'.
# np.histogram returns the bin edges, so there will be 50 probability
# density values in n, 51 bin edges in bins and 50 patches.  To get
# everything lined up, we'll compute the bin centers
bincenters = 0.5*(bins[1:]+bins[:-1])
# add a 'best fit' line for the normal PDF
y = mlab.normpdf( bincenters, mu, sigma)
l = ax.plot(bincenters, y, 'r--', linewidth=1)

ax.set_xlabel('Smarts')
ax.set_ylabel('Probability')
#ax.set_title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
ax.set_xlim(40, 160)
ax.set_ylim(0, 0.03)
ax.grid(True)

plt.show()

【问题讨论】:

  • 您能否准确描述一下您如何在 spyder 中运行此代码?每次都是新的 IPython 控制台吗?您想使用 IPython 并内联显示图形,还是希望它显示为自己的图形窗口?
  • 我在 IPython 控制台中运行它并作为 .py 文件运行。每次都是同一个 IPython 控制台,但我在运行前使用 %reset 来清除变量。当我在编辑器中使用 F9 逐行运行它时, plt.show() 什么也不做。如果我将 .py 文件作为一个整体运行,则该图将显示文件中是否包含 plt.show() 或已注释掉。很高兴知道如何将图形显示为自己的图形窗口。
  • 如果您不需要 IPython 控制台,this answer 可能就是您要找的。那么有理由使用 IPython 控制台吗?如果是这样,是否需要能够逐行处理代码?您越准确地说明您的需求,获得满意解决方案的机会就越大。
  • %matplotlib 仅适用于 IPython,不适用于“专用 Python 控制台”。如果您想在 Spyder 内的 IPython 控制台中使用某些特定的后端,您需要在首选项中选择它。 “TK”或“QT”应该可以工作(这将创建一个新窗口)。但是,只有在创建绘图时将plt.show() 写入同一单元格时,这才有可能。您可能希望在新的专用控制台中运行脚本,但使用 IPython 进行尝试。
  • x.show() 未定义。应该是plt.show()。也许看看this screenshot。但是,在这种情况下,您甚至不需要 plt.show()

标签: python matplotlib


【解决方案1】:

更改您的 IPython 控制台图形设置。

如果您使用的是 Spyder,请按以下步骤操作:

  1. 转到Tools
  2. 转到Preferences
  3. 选择IPython console
  4. 转到Graphics 选项卡。
  5. Graphics backend 部分下,选择Automatic 作为后端类型。

然后,重新启动内核。

【讨论】:

  • 非常适合我。但是作为 Spyder 的新手,弄清楚“重新启动内核”部分需要一些时间。也很高兴将其添加到您的答案中。在那之前,如果有人也在寻找相同的东西,您需要转到控制台中的选项(三个水平条)并选择“重新启动内核”..
  • “自动”对我不起作用。我必须将后端设置为“内联”(让它显示在绘图面板上)。
【解决方案2】:

使用plt.draw() 而不是plt.show()。这对我有用。这是我找到的参考资料:https://github.com/spyder-ide/spyder/issues/2402

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2012-09-30
    • 1970-01-01
    • 2020-06-07
    • 2015-09-12
    • 2019-06-11
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    相关资源
    最近更新 更多