5

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)

B Davis
  • 53
  • 1
  • 3

1 Answers1

10

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

realr
  • 3,652
  • 6
  • 23
  • 34
  • 2
    This fixed it! I realized this solution [here](https://stackoverflow.com/questions/42163470/how-to-execute-a-py-file-from-a-ipynb-file-on-the-jupyter-notebook) only after I posted the original question, but this result did not come up in any of my original search queries, so I'd argue that this is not a duplicate question. – B Davis Jul 21 '19 at 18:11
  • Hi @BDavis, it is not yet clear the actual differences between running `!ipython` and `%run` in Jupyter Notebooks and perhaps that could be a question on its own, to try to understand what happens under the hood for both commands. – realr Jul 21 '19 at 18:14
  • 1
    Thank you so much! I was stuck on this for weeks and it was driving me insane. – LeggoMaEggo Sep 21 '21 at 22:51