当我在jupyter笔记本中使用matplotlib时,它总是引发"matplotlib目前正在使用非GUI后端"错误?

Yuh*_* Li 36 python matplotlib jupyter-notebook

import matplotlib.pyplot as pl
%matplot inline
def learning_curves(X_train, y_train, X_test, y_test):
""" Calculates the performance of several models with varying sizes of training data.
    The learning and testing error rates for each model are then plotted. """

print ("Creating learning curve graphs for max_depths of 1, 3, 6, and 10. . .")

# Create the figure window
fig = pl.figure(figsize=(10,8))

# We will vary the training set size so that we have 50 different sizes
sizes = np.rint(np.linspace(1, len(X_train), 50)).astype(int)
train_err = np.zeros(len(sizes))
test_err = np.zeros(len(sizes))

# Create four different models based on max_depth
for k, depth in enumerate([1,3,6,10]):

    for i, s in enumerate(sizes):

        # Setup a decision tree regressor so that it learns a tree with max_depth = depth
        regressor = DecisionTreeRegressor(max_depth = depth)

        # Fit the learner to the training data
        regressor.fit(X_train[:s], y_train[:s])

        # Find the performance on the training set
        train_err[i] = performance_metric(y_train[:s], regressor.predict(X_train[:s]))

        # Find the performance on the testing set
        test_err[i] = performance_metric(y_test, regressor.predict(X_test))

    # Subplot the learning curve graph
    ax = fig.add_subplot(2, 2, k+1)

    ax.plot(sizes, test_err, lw = 2, label = 'Testing Error')
    ax.plot(sizes, train_err, lw = 2, label = 'Training Error')
    ax.legend()
    ax.set_title('max_depth = %s'%(depth))
    ax.set_xlabel('Number of Data Points in Training Set')
    ax.set_ylabel('Total Error')
    ax.set_xlim([0, len(X_train)])

# Visual aesthetics
fig.suptitle('Decision Tree Regressor Learning Performances', fontsize=18, y=1.03)
fig.tight_layout()
fig.show()
Run Code Online (Sandbox Code Playgroud)

当我运行该learning_curves()功能时,它显示:

UserWarning:C:\ Users\Administrator\Anaconda3\lib\site-packages\matplotlib\figure.py:397:UserWarning:matplotlib目前正在使用非GUI后端,因此无法显示图

这是截图

Yul*_*Yul 45

你不需要"fig.show()"这一行.只需删除它.然后它将没有警告信息.

  • 不会有警告消息,但是会显示该图。我正在Pycharm上工作,当没有执行fig.show()时,它甚至不显示图。请问该怎么办? (8认同)
  • 换句话说,一个选择就是将最后一行简单地设置为“fig” (4认同)
  • 如果绘图是笔记本单元格中的最后一个对象,则 jupyter 会尝试渲染它。如果您有多个绘图或进一步的输出,并且排除“fig.show()”,那么您将看不到图形。 (3认同)

小智 23

导入时内联添加%matplotlib有助于在笔记本中平滑绘图

%matplotlib inline
import matplotlib.pyplot as plt
Run Code Online (Sandbox Code Playgroud)

%matplotlib内联matplotlib的后端设置为'inline'后端:在该后端,绘图命令的输出以内联方式显示在Jupyter笔记本之类的前端中,位于生成它的代码单元正下方。然后,生成的图也将存储在笔记本文档中。

  • 谢谢。我在安装并使用 pandas 图形分析后遇到了问题。仅使用一次“%matplotlib inline”就解决了我的 jupyter 笔记本的问题。 (2认同)

air*_*das 17

您可以通过包括以下内容来更改matplotlib使用的后端:

import matplotlib
matplotlib.use('TkAgg')
Run Code Online (Sandbox Code Playgroud)

第1行之前import matplotlib.pyplot as pl,因为必须先设置它.有关更多信息,请参阅此答案.

(还有其他后端选项,但是TkAgg当我遇到类似的问题时,改变后端为我工作)


Cle*_*oom 8

与测试https://matplotlib.org/examples/animation/dynamic_image.html我只是添加

%matplotlib notebook
Run Code Online (Sandbox Code Playgroud)

这似乎有效,但有点颠簸。我不得不时不时地停止内核:-(

  • `%matplotlib notebook` 提供了交互式、可平移和可缩放的图表。 (2认同)

小智 7

我试图制作类似于Towards Data Science Tutorial 的3d 聚类。我最初认为fig.show()可能是正确的,但得到了同样的警告......简要地查看了Matplot3d .. 但后来我尝试了plt.show()它,它完全按照预期显示了我的 3d 模型。我想这也有道理。这相当于你的pl.show()

使用 python 3.5 和 Jupyter Notebook

  • 您能否编辑您的答案来解释如何解决问题,而不是解释您经历的过程?您还应该考虑将来查看[如何回答](https://stackoverflow.com/help/how-to-answer)文章:) (2认同)

小智 6

您仍然可以通过 fig.savefig() 保存图形

如果想在网页上查看,可以试试

from IPython.display import display
display(fig)
Run Code Online (Sandbox Code Playgroud)

  • 这有效,就像上面的注释一样,仅使用“fig”作为单元格的最后一行 (2认同)

Ton*_*y P 5

当我尝试使用命令显示绘图时,也会出现错误“matplotlib 当前正在使用非 GUI 后端” fig.show()。我发现在 Jupyter Notebook 中,命令fig, ax = plt.subplots()和绘图命令需要在同一个单元格中。为要渲染的情节。

例如,以下代码将在 Out[5] 中成功显示条形图:

在 [3] 中:

import matplotlib.pyplot as plt
%matplotlib inline
Run Code Online (Sandbox Code Playgroud)

在 [4] 中:

x = 'A B C D E F G H'.split()
y = range(1, 9)
Run Code Online (Sandbox Code Playgroud)

在 [5]:

fig, ax = plt.subplots()
ax.bar(x, y)
Run Code Online (Sandbox Code Playgroud)

Out[5]:(8位艺术家的容器对象)

成功的条形图输出

另一方面,以下代码不会显示情节,

在 [5]:

fig, ax = plt.subplots()
Run Code Online (Sandbox Code Playgroud)

出[5]:

只有一个框架的空图

在 [6] 中:

ax.bar(x, y)
Run Code Online (Sandbox Code Playgroud)

Out[6]:(8位艺术家的容器对象)

在 Out[6] 中,只有“8 个艺术家的容器对象”的声明,但没有显示条形图。


Imr*_*lob 5

只需键入fig而不是fig.show()