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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37365357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:17:39  来源:igfitidea点击:

when i use matplotlib in jupyter notebook,it always raise " matplotlib is currently using a non-GUI backend" error?

pythonmatplotlibjupyter-notebook

提问by Yuhao Li

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

when I run the learning_curves()function, it shows:

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

UserWarning:C:\Users\Administrator\Anaconda3\lib\site-packages\matplotlib\figure.py:397: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure

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

this is the screenshot

这是截图

回答by Yul

You don't need the line of "fig.show()". Just remove it. Then it will be no warning message.

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

回答by Mulugeta Weldezgina

adding %matplotlib inlinewhile importing helps for smooth plots in notebook

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

%matplotlib inline
import matplotlib.pyplot as plt

%matplotlib inlinesets the backend of matplotlib to the 'inline' backend: With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

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

回答by airdas

You can change the backend used by matplotlib by including:

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

import matplotlib
matplotlib.use('TkAgg')

beforeyour line 1 import matplotlib.pyplot as pl, as it must be set first. See this answerfor more information.

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

(There are other backend options, but changing backend to TkAggworked for me when I had a similar problem)

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

回答by Clemens Tolboom

Testing with https://matplotlib.org/examples/animation/dynamic_image.htmlI just add

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

%matplotlib notebook

which seems to work but is a little bumpy. I had to stop the kernal now and then :-(

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

回答by GAINZ

I was trying to make 3d clustering similar to Towards Data Science Tutorial. I first thought fig.show()might be correct, but got the same warning... Briefly viewed Matplot3d.. but then I tried plt.show()and it displayed my 3d model exactly as anticipated. I guess it makes sense too. This would be equivalent to your pl.show()

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

Using python 3.5 and Jupyter Notebook

使用 python 3.5 和 Jupyter Notebook

回答by Tony P

The error "matplotlib is currently using a non-GUI backend” also occurred when I was trying to display a plot using the command fig.show(). I found that in a Jupyter Notebook, the command fig, ax = plt.subplots()and a plot command need to be in the same cell in order for the plot to be rendered.

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

For example, the following code will successfully show a bar plot in Out[5]:

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

In [3]:

在 [3] 中:

import matplotlib.pyplot as plt
%matplotlib inline

In [4]:

在 [4] 中:

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

In [5]:

在 [5]:

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

Out[5]: (Container object of 8 artists)

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

A successful bar plot output

成功的条形图输出

On the other hand, the following code will not show the plot,

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

In [5]:

在 [5]:

fig, ax = plt.subplots()

Out[5]:

出[5]:

An empty plot with only a frame

只有一个框架的空图

In [6]:

在[6]:

ax.bar(x, y)

Out[6]: (Container object of 8 artists)

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

In Out[6] there is only a statement of "Container object of 8 artists" but no bar plot is shown.

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

回答by beforelongbefore

You can still save the figure by fig.savefig()

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

If you want to view it on the web page, you can try

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

from IPython.display import display
display(fig)

回答by Anvesh

If you are using any profiling libraries like pandas_profiling, try commenting out them and execute the code. In my case I was using pandas_profiling to generate a report for a sample train data. commenting out import pandas_profiling helped me solve my issue.

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

回答by praveen balaji

I had the same error. Then I used

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

import matplotlib matplotlib.use('WebAgg')

import matplotlib matplotlib.use('WebAgg')

it works fine.(You have to install tornado to view in web, (pip install tornado))

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

Python version: 3.7 matplotlib version: 3.1.1

Python 版本:3.7 matplotlib 版本:3.1.1

回答by aditya singhal

%matplotlib notebook worked for me.

%matplotlib 笔记本对我有用。

But the takes time to load and but it is clear.

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