繁体   English   中英

当我在 jupyter notebook 中使用 matplotlib 时,它总是引发“matplotlib 当前正在使用非 GUI 后端”错误?

[英]When I use matplotlib in jupyter notebook,it always raise “ matplotlib is currently using a non-GUI backend” error?

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

当我运行learning_curves()函数时,它显示:

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

这是截图

您不需要“fig.show()”这一行。 只需将其删除。 那么它将没有警告消息。

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

%matplotlib inline
import matplotlib.pyplot as plt

%matplotlib inlinematplotlib的后端设置为“内联”后端:使用此后端,绘图命令的输出内联显示在 Jupyter 笔记本等前端内,直接在生成它的代码单元下方。 结果图也将存储在笔记本文档中。

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

import matplotlib
matplotlib.use('TkAgg')

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

(还有其他后端选项,但是当我遇到类似问题时,将后端更改为TkAgg对我TkAgg

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

%matplotlib notebook

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

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

使用 python 3.5 和 Jupyter Notebook

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

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

from IPython.display import display
display(fig)

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

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

在 [3] 中:

import matplotlib.pyplot as plt
%matplotlib inline

在 [4] 中:

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

在 [5]:

fig, ax = plt.subplots()
ax.bar(x, y)

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

成功的条形图输出

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

在 [5]:

fig, ax = plt.subplots()

出[5]:

只有一个框架的空图

在 [6] 中:

ax.bar(x, y)

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

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

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

如果您正在使用任何分析库,如 pandas_profiling,请尝试将它们注释掉并执行代码。 在我的例子中,我使用 pandas_profiling 为样本列车数据生成报告。 注释掉 import pandas_profiling 帮助我解决了我的问题。

我有同样的错误。 然后我用

import matplotlib matplotlib.use('WebAgg')

它工作正常。(你必须安装 tornado 才能在 web 中查看,( pip install tornado ))

Python 版本:3.7 matplotlib 版本:3.1.1

%matplotlib 笔记本对我有用。

但是加载需要时间,而且很明显。

您将 matplotlib.pyplot 导入为pl 最后输入pl .show() 而不是fig .show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM