Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib plot from Python script not showing up in output when run in Jupyter Notebook

Trying to run a Python script from the directory that my Jupyter notebook is in. The script executes as expected, but the plot does not show up in the output in my Jupyter Notebook.

I have tried adding code like plt.show() to the test script, but it doesn't show the graph in the Jupyter output. I have also tried adding %matplotlib inline to the Jupyter cell, but that doesn't help either.

In Jupyter Notebook cell:

import matplotlib as plt
%matplotlib inline
!python test_plot.py

In the test_plot.py Python script:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

Expected Results: When I run the code straight in the notebook,

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

it produces a piecewise function. (Can't post image due to low reputation). However, this is not the actual result.

Actual results printed in Jupyter Cell: Figure(640x480)

like image 318
B Davis Avatar asked Jul 21 '19 17:07

B Davis


People also ask

Why is matplotlib not showing plot?

It means if we are not using the show() function, it wouldn't show any plot. When we use the show() function in the non-interactive mode. That means when we write the code in the file it will show all the figures or plots and blocks until the plots have been closed.

How do you display plots in Jupyter notebook?

Usually, displaying plots involves using the show() function from PyPlot. With Jupyter notebooks, this isn't necessary as the plots are displayed after running the cells containing the code that generates them. These plots are by default, displayed inline, which means, they're displayed in the notebook itself.

How do I use matplotlib in Jupyter notebook?

Install Matplotlib Make sure you first have Jupyter notebook installed, then we can add Matplotlib to our virtual environment. To do so, navigate to the command prompt and type pip install matplotlib. Now launch your Jupyter notebook by simply typing jupyter notebook at the command prompt.


1 Answers

Try using:

%run 'test_plot.py'

as opposed to

!python test_plot.py

You should be able to run the cell correctly with the desired chart being plotted

like image 157
calestini Avatar answered Oct 19 '22 20:10

calestini