简体   繁体   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()

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 后端,因此无法显示图

这是截图

You don't need the line of "fig.show()".您不需要“fig.show()”这一行。 Just remove it.只需将其删除。 Then it will be no warning message.那么它将没有警告消息。

adding %matplotlib inline while importing helps for smooth plots in notebook在导入时内联添加%matplotlib有助于在笔记本中平滑绘图

%matplotlib inline
import matplotlib.pyplot as plt

%matplotlib inline sets 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. %matplotlib inlinematplotlib的后端设置为“内联”后端:使用此后端,绘图命令的输出内联显示在 Jupyter 笔记本等前端内,直接在生成它的代码单元下方。 The resulting plots will then also be stored in the notebook document.结果图也将存储在笔记本文档中。

You can change the backend used by matplotlib by including:您可以通过包括以下内容来更改 matplotlib 使用的后端:

import matplotlib
matplotlib.use('TkAgg')

before your line 1 import matplotlib.pyplot as pl , as it must be set first.第 1 行之前import matplotlib.pyplot as pl ,因为它必须首先设置。 See this answer for more information.有关更多信息,请参阅此答案

(There are other backend options, but changing backend to TkAgg worked for me when I had a similar problem) (还有其他后端选项,但是当我遇到类似问题时,将后端更改为TkAgg对我TkAgg

Testing with https://matplotlib.org/examples/animation/dynamic_image.html I 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 :-(我不得不时不时地停止内核:-(

I was trying to make 3d clustering similar to Towards Data Science Tutorial .我试图制作类似于Towards Data Science Tutorial 的3d 聚类。 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.我首先认为fig.show()可能是正确的,但得到了同样的警告......简要地查看了Matplot3d .. 但后来我尝试了plt.show()并且它完全按照预期显示了我的 3d 模型。 I guess it makes sense too.我想这也有道理。 This would be equivalent to your pl.show()这相当于你的pl.show()

Using python 3.5 and Jupyter Notebook使用 python 3.5 和 Jupyter Notebook

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)

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.当我尝试使用命令fig.show()显示绘图时,也会出现错误“matplotlib 当前正在使用非 GUI 后端”。我发现在 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 个艺术家的容器对象”的声明,但没有显示条形图。

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

If you are using any profiling libraries like pandas_profiling, try commenting out them and execute the code.如果您正在使用任何分析库,如 pandas_profiling,请尝试将它们注释掉并执行代码。 In my case I was using pandas_profiling to generate a report for a sample train data.在我的例子中,我使用 pandas_profiling 为样本列车数据生成报告。 commenting out import pandas_profiling helped me solve my issue.注释掉 import pandas_profiling 帮助我解决了我的问题。

I had the same error.我有同样的错误。 Then I used然后我用

import matplotlib matplotlib.use('WebAgg')

it works fine.(You have to install tornado to view in web, ( pip install tornado ))它工作正常。(你必须安装 tornado 才能在 web 中查看,( pip install tornado ))

Python version: 3.7 matplotlib version: 3.1.1 Python 版本:3.7 matplotlib 版本:3.1.1

%matplotlib notebook worked for me. %matplotlib 笔记本对我有用。

But the takes time to load and but it is clear.但是加载需要时间,而且很明显。

You imported matplotlib.pyplot as pl .您将 matplotlib.pyplot 导入为pl In the end type pl .show() instead of fig .show()最后输入pl .show() 而不是fig .show()

暂无
暂无

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

相关问题 “用户警告:Matplotlib 当前正在使用非 GUI 后端的 agg,因此无法显示图形。” 在 Pycharm 上用 pyplot 绘制图形时 - "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm 为什么得到用户警告:Matplotlib当前正在使用ps,这是非GUI后端,因此无法显示该图 - Why am I getting UserWarning: Matplotlib is currently using ps, which is a non-GUI backend, so cannot show the figure 在一个源代码中,我输入它并得到: UserWarning:Matplotlib 当前正在使用 agg,这是一个非 GUI 后端,所以无法显示图 - In a source code, I typed it in and got: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure 用户警告:Matplotlib 当前使用 agg,这是一个非 GUI 后端,因此无法显示图 - UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure PyCharm Matplotlib "UserWarning: Matplotlib 当前正在使用 agg,这是一个非 GUI 后端,所以无法显示图。plt.show()" - PyCharm Matplotlib "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. plt.show()" jupyter笔记本%matplotlib错误 - jupyter notebook %matplotlib error 无法在 Jupyter Notebook 中使用 GTK3Agg Matplotlib 后端 - Failing to use the GTK3Agg Matplotlib backend in Jupyter Notebook [matplotlib]:在Jupyter%matplotlib笔记本上使用ginput - [matplotlib]: use of ginput on Jupyter %matplotlib notebook m1 mac,python 在 matplotlib 和 jupyter 笔记本中使用 osx 作为后端时断言失败和崩溃 - m1 mac, python assertion failure and crashes when using osx as backend in matplotlib & jupyter notebook 在非GUI机器(Web服务器)上运行时,matplotlib引发分段错误 - matplotlib is throwing segmentation fault when running on non-gui machine(web server)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM