76
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

peterh
  • 11,875
  • 18
  • 85
  • 108
Yuhao Li
  • 777
  • 1
  • 5
  • 4

11 Answers11

91

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

petezurich
  • 9,280
  • 9
  • 43
  • 57
Yul
  • 3,216
  • 2
  • 18
  • 13
  • 14
    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? – SKR Nov 17 '18 at 04:21
  • 5
    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 the`fig.show()`s then you won't see your graphics. – Dave X Oct 25 '19 at 17:18
  • 4
    In other words, one option is to simply have the last line be `fig` – Matt VanEseltine Nov 05 '20 at 20:40
  • beforelongbefore's answer to use `IPython.display` is better, though, as it works with multiple figures per cell. – Marius Wallraff Oct 07 '21 at 13:06
  • 1
    @SKR Make your last line `fig.tight_layout()` – Hadij Mar 03 '22 at 19:24
51

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.

  • This works in particular with the new jupyter implementation in PyCharm 2019.1+ – Holger Brandl Mar 01 '19 at 12:08
  • 2
    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. – user96265 Oct 25 '21 at 22:07
28

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)

Community
  • 1
  • 1
airdas
  • 872
  • 2
  • 11
  • 19
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 :-(

Clemens Tolboom
  • 1,872
  • 18
  • 30
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)
11

Just type fig instead of fig.show()

Imran Pollob
  • 453
  • 6
  • 8
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

GAINZ
  • 177
  • 2
  • 4
  • 2
    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](https://stackoverflow.com/help/how-to-answer) article for the future :) – Marcello B. Oct 16 '18 at 04:44
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.

Tony Peng
  • 579
  • 5
  • 10
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

desertnaut
  • 57,590
  • 26
  • 140
  • 166
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.

Anvesh
  • 13
  • 3
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 ...

marcio
  • 566
  • 7
  • 19