【发布时间】: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