85
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

6
  • 2
    What version of matplotlib are you using? You can check with import matplotlib and print(matplotlib.__version__) Commented May 21, 2016 at 16:50
  • 1.5.1 ,the newest version. Commented May 22, 2016 at 3:05
  • 7
    Adding "%pylab inline" works for me. Commented Apr 6, 2018 at 13:57
  • None of the solutions worked for me. Matplotlib version 3.0.3. Commented Dec 5, 2019 at 15:44
  • 3
    The correct answer, though not explained well, is stackoverflow.com/a/52827912/290182 - use pl.show(), not fig.show(). Commented Apr 8, 2020 at 19:37

11 Answers 11

97

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

Sign up to request clarification or add additional context in comments.

5 Comments

There will be no warning message but then how one would see the figure. I am working on Pycharm and when executed without fig.show() it doesn't even show the plots. What is the way around please?
If the plot is the last object in a notebook cell, then jupyter tries to render it. If you have more than one plot or further output, and exclude thefig.show()s then you won't see your graphics.
In other words, one option is to simply have the last line be fig
beforelongbefore's answer to use IPython.display is better, though, as it works with multiple figures per cell.
@SKR Make your last line fig.tight_layout()
56

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.

3 Comments

This works in particular with the new jupyter implementation in PyCharm 2019.1+
Thank you. I got the problem after installing and using pandas profiling for graphics. Using "%matplotlib inline" just once fixed the problem with my jupyter notebook.
%matplotlib inline solves the issue for me when I was working with Visual Studio Code.
29

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)

Comments

14

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

2 Comments

%matplotlib notebook gives an interactive, panable, and zoomable graphs.
this worked for me! thanx! I just have to use for validation purposes, dont need the graph in production, so it works for me.
14

Just type fig instead of fig.show()

Comments

11

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)

2 Comments

this works, as does the comment above to just use fig as the last line of a cell
Right, but this one is better because it works with multiple figures in one cell.
10

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

1 Comment

Can you please edit your answer to explain how to solve the problem, instead of explaining the process you went through? You should also consider looking at the how to answer article for the future :)
7

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.

Comments

2

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

Comments

0

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.

Comments

0

Solution 1:
Replace the fig.show() line by None, just that !!!

Solution 2:
Finish the last line before the fig.show() with an ; (semicolon) and remove the fig.show() line.

I prefer the solution 1, more explicit.

I lost the references ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.