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

PythonMatplotlibJupyter Notebook

Python Problem Overview


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:

> 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

this is the screenshot

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

adding %matplotlib inline while importing helps for smooth plots in notebook

%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. The resulting plots will then also be stored in the notebook document.

Solution 3 - Python

You can change the backend used by matplotlib by including:

import matplotlib
matplotlib.use('TkAgg')

before your line 1 import matplotlib.pyplot as pl, as it must be set first. 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)

Solution 4 - Python

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

%matplotlib notebook

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

Solution 5 - Python

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

Using python 3.5 and Jupyter Notebook

Solution 6 - Python

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

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

from IPython.display import display
display(fig)

Solution 7 - Python

Just type fig instead of fig.show()

Solution 8 - Python

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.

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

In [3]:

import matplotlib.pyplot as plt
%matplotlib inline

In [4]:

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

In [5]:

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

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

A successful bar plot output

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

In [5]:

fig, ax = plt.subplots()

Out[5]:

An empty plot with only a frame

In [6]:

ax.bar(x, y)

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

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

Solution 9 - Python

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.

Solution 10 - Python

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

Python version: 3.7 matplotlib version: 3.1.1

Solution 11 - Python

%matplotlib notebook worked for me.

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

Solution 12 - Python

You imported matplotlib.pyplot as pl. In the end type pl.show() instead of fig.show()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYuhao LiView Question on Stackoverflow
Solution 1 - PythonYulView Answer on Stackoverflow
Solution 2 - PythonMulugeta WeldezginaView Answer on Stackoverflow
Solution 3 - PythonairdasView Answer on Stackoverflow
Solution 4 - PythonClemens TolboomView Answer on Stackoverflow
Solution 5 - PythonGAINZView Answer on Stackoverflow
Solution 6 - PythonbeforelongbeforeView Answer on Stackoverflow
Solution 7 - PythonImran PollobView Answer on Stackoverflow
Solution 8 - PythonTony PView Answer on Stackoverflow
Solution 9 - PythonAnveshView Answer on Stackoverflow
Solution 10 - Pythonpraveen balajiView Answer on Stackoverflow
Solution 11 - Pythonaditya singhalView Answer on Stackoverflow
Solution 12 - PythonStepan BabayanView Answer on Stackoverflow