I’ve recently moved over to using IPython notebooks as part of my workflow. However, I’ve not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done?
I’ve found this in the documentation which tells me how to import .py files as new notebooks but this falls short of what I want to achieve.
EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to
load/edit/save text files.
A text file can be loaded in a notebook cell with the magic command %load.
If you execute a cell containing:
%load filename.py
the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.
To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.
To see the help for any magic command add a ?: like %load? or %%writefile?.
For general help on magic functions type “%magic”
For a list of the available magic functions, use %lsmagic. For a description
of any of them, type %magic_name?, e.g. ‘%cd?’.
write/save cell contents into myfile.py (use -a to append). Another alias: %%file myfile.py
To run
%run myfile.py
run myfile.py and output results in the current cell
To load/import
%load myfile.py
load “import” myfile.py into the current cell
For more magic and help
%lsmagic
list all the other cool cell magic commands.
%COMMAND-NAME?
for help on how to use a certain command. i.e. %run?
Note
Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the %%bash cell magic command).
To run a unix command from the cell, just precede your command with ! mark. for example:
!python --version see your python version
!python myfile.py run myfile.py and output results in the current cell, just like %run (see the difference between !python and %run in the comments below).
Also, see this nbviewer for further explanation with examples.
Hope this helps.
Drag and drop a Python file in the Ipython notebooks “home” notebooks table, click upload. This will create a new notebook with only one cell containing your .py file content
I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you’ll get back the contents of the file, which you can then paste into the cell as code.
If you only want the image of your figure to appear larger without changing the general appearance of your figure increase the figure resolution. Changing the figure size as suggested in most other answers will change the appearance since font sizes do not scale accordingly.
import matplotlib.pylab as plt
plt.rcParams['figure.dpi'] = 200
You mustn’t use quotation marks around the name of the image files in markdown!
If you carefully read your error message, you will see the two %22 parts in the link. That is the html encoded quotation mark.
You have to change the line
![title]("img/picture.png")
to
![title](img/picture.png)
UPDATE
It is assumed, that you have the following file structure and that you run the jupyter notebook command in the directory where the file example.ipynb (<– contains the markdown for the image) is stored:
/
+-- example.ipynb
+-- img
+-- picture.png
回答 1
有几种方法可以在Jupyter笔记本中发布图像:
通过HTML:
fromIPython.display importImagefromIPython.core.display import HTML
Image(url="http://my_site.com/my_picture.jpg")
if the image it wider than the display settings:thanks
use unconfined=True to disable max-width confinement of the image
from IPython.core.display import Image, display
display(Image('https://i.ytimg.com/vi/j22DmsZEv30/maxresdefault.jpg', width=1900, unconfined=True))
or via markdown:
make sure the cell is a markdown cell, and not a code cell, thanks @游凯超 in the comments)
Please note that on some systems, the markdown does not allow white space in the filenames. Thanks to @CoffeeTableEspresso and @zebralamy in the comments)
(On macos, as long as you are on a markdown cell you would do like this: ![title](../image 1.png), and not worry about the white space).
for a web image:
![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)
as shown by @cristianmtr
Paying attention not to use either these quotes "" or those '' around the url.
I know this is not fully relevant, but since this answer is ranked first many a times when you search ‘how to display images in Jupyter‘, please consider this answer as well.
You could use matplotlib to show an image as follows.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread("your_image.png")
plt.imshow(image)
plt.show()
In addition to the other answers using HTML (either in Markdown or using the %%HTML magic:
If you need to specify the image height, this will not work:
<img src="image.png" height=50> <-- will not work
That is because the CSS styling in Jupyter uses height: auto per default for the img tags, which overrides the HTML height attribute. You need need to overwrite the CSS height attribute instead:
<img src="image.png" style="height:50px"> <-- works
Insert the image directly in the Jupyter notebook.
Note: You should have a local copy of the image on your computer
You can insert the image in the Jupyter notebook itself. This way you don’t need to keep the image separately in the folder.
Steps:
Convert the cell to markdown by:
pressing M on the selected cell
OR
From menu bar, Cell > Cell Type > Markdown.
(Note: It’s important to convert the cell to Markdown, otherwise the “Insert Image” option in Step 2 will not be active)
Now go to menu bar and select Edit -> Insert Image.
Select image from your disk and upload.
Press Ctrl+Enter or Shift+Enter.
This will make the image as part of the notebook and you don’t need to upload in the directory or Github. I feel this looks more clean and not prone to broken URL issue.
回答 7
使用Markdown的方法如下:
![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)
Drag and drop your image into the cell. The following command will be created:
![image.png](attachment:image.png)
Execute/Run the cell and the image shows up.
The image is actually embedded in the ipynb Notebook and you don’t need to mess around with separate files. This is unfortunately not working with Jupyter-Lab (v 1.1.4) yet.
If you want to use the Jupyter Notebook API (and not the IPython one anymore), I find the ipywidgets Jupyter’s sub-project. You have an Image widget. Docstring specifies that you have a value parameter which is a bytes. So you can do:
import requests
from ipywidgets import Image
Image(value=requests.get('https://octodex.github.com/images/yaktocat.png').content)
I agree, it’s simpler to use the Markdown style. But it shows you the Image display Notebook API. You can also resize the image with the width and height parameters.
One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.
回答 13
同意,我遇到了同样的问题,这是可行的,而没有奏效的:
WORKED:<img src="Docs/pinoutDOIT32devkitv1.png" width="800"/>*DOES NOT WORK:<img src="/Docs/pinoutDOIT32devkitv1.png" width="800"/>
DOES NOT WORK:<img src="./Docs/pinoutDOIT32devkitv1.png" width="800"/>*
要在浏览器中查看图像,您可以访问data:image/png;base64,**image data here**以base64编码的PNG图像或data:image/jpg;base64,**image data here**以base64编码的JPG图像的链接。在此答案的末尾可以找到一个示例链接。
While a lot of the above answers give ways to embed an image using a file or with Python code, there is a way to embed an image in the jupyter notebook itself using only markdown and base64!
To view an image in the browser, you can visit the link data:image/png;base64,**image data here** for a base64-encoded PNG image, or data:image/jpg;base64,**image data here** for a base64-encoded JPG image. An example link can be found at the end of this answer.
To embed this into a markdown page, simply use a similar construct as the file answers, but with a base64 link instead: ![**description**](data:image/**type**;base64,**base64 data**). Now your image is 100% embedded into your Jupyter Notebook file!
Example link: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==
Example markdown:
![smile](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==)
I would like to increase the width of the ipython notebook in my browser. I have a high-resolution screen, and I would like to expand the cell width/size to make use of this extra space.
If you don’t want to change your default settings, and you only want to change the width of the current notebook you’re working on, you can enter the following into a cell:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
/* Make the notebook cells take almost all available width */.container {width:99%!important;}/* Prevent the edit cell highlight box from getting clipped;
* important so that it also works when cell is in edit mode*/
div.cell.selected {border-left-width:1px!important;}
To get this to work with jupyter (version 4.0.6) I created ~/.jupyter/custom/custom.css containing:
/* Make the notebook cells take almost all available width */
.container {
width: 99% !important;
}
/* Prevent the edit cell highlight box from getting clipped;
* important so that it also works when cell is in edit mode*/
div.cell.selected {
border-left-width: 1px !important;
}
What I do usually after new installation is to modify the main css file where all visual styles are stored. I use Miniconda but location is similar with others C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css
With some screens these resolutions are different and more than 1. To be on the safe side I change all to 98% so if I disconnect from my external screens on my laptop I still have 98% screen width.
Then just replace 1140px with 98% of the screen width.
(As of 2018, I would advise trying out JupyterHub/JupyterLab. It uses the full width of the monitor. If this is not an option, maybe since you are using one of the cloud-based Jupyter-as-a-service providers, keep reading)
(Stylish is accused of stealing user data, I have moved on to using Stylus plugin instead)
I recommend using Stylish Browser Plugin. This way you can override css for all notebooks, without adding any code to notebooks.
We don’t like to change configuration in .ipython/profile_default, since we are running a shared Jupyter server for the whole team and width is a user preference.
I made a style specifically for vertically-oriented high-res screens, that makes cells wider and adds a bit of empty-space in the bottom, so you can position the last cell in the centre of the screen.
https://userstyles.org/styles/131230/jupyter-wide
You can, of course, modify my css to your liking, if you have a different layout, or you don’t want extra empty-space in the end.
Last but not least, Stylish is a great tool to have in your toolset, since you can easily customise other sites/tools to your liking (e.g. Jira, Podio, Slack, etc.)
For Chrome users, I recommend Stylebot, which will let you override any CSS on any page, also let you search and install other share custom CSS. However, for our purpose we don’t need any advance theme. Open Stylebot, change to Edit CSS. Jupyter captures some keystrokes, so you will not be able to type the code below in. Just copy and paste, or just your editor:
#notebook-container.container {
width: 90%;
}
Change the width as you like, I find 90% looks nicer than 100%. But it is totally up to your eye.
/*Make the notebook cells take almost all available width and limit minimal width to 1110px*/.container {
width:99%;
min-width:1110px;}/*Prevent the edit cell highlight box from getting clipped;* important so that it also works when cell isin edit mode*/
div.cell.selected {
border-left-width:1px;}
I made some modification to @jvd10’s solution. The ‘!important’ seems too strong that the container doesn’t adapt well when TOC sidebar is displayed. I removed it and added ‘min-width’ to limit the minimal width.
Here is my .juyputer/custom/custom.css:
/* Make the notebook cells take almost all available width and limit minimal width to 1110px */
.container {
width: 99%;
min-width: 1110px;
}
/* Prevent the edit cell highlight box from getting clipped;
* important so that it also works when cell is in edit mode*/
div.cell.selected {
border-left-width: 1px;
}
回答 10
我尝试了一切,但对我没有用,最终我将数据框显示为HTML,如下所示
fromIPython.display import HTML
HTML (pd.to_html())
%matplotlib is a magic function in IPython. I’ll quote the relevant documentation here for you to read for convenience:
IPython has a set of predefined ‘magic functions’ that you can call with a command line style syntax. There are two kinds of magics, line-oriented and cell-oriented. Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Lines magics can return results and can be used in the right hand side of an assignment. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.
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.
When using the ‘inline’ backend, your matplotlib graphs will be included in your notebook, next to the code. It may be worth also reading How to make IPython notebook matplotlib plot inline for reference on how to use it in your code.
If you want interactivity as well, you can use the nbagg backend with %matplotlib notebook (in IPython 3.x), as described here.
To set this up, before any plotting or import of matplotlib is
performed you must execute the %matplotlib magic command. This
performs the necessary behind-the-scenes setup for IPython to work
correctly hand in hand with matplotlib; it does not, however,
actually execute any Python import commands, that is, no names are
added to the namespace.
A particularly interesting backend, provided by IPython, is the
inline backend. This is available only for the Jupyter Notebook and
the Jupyter QtConsole. It can be invoked as follows:
%matplotlib inline
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.
If you want to add plots to your Jupyter notebook, then %matplotlib inline is a standard solution. And there are other magic commands will use matplotlib interactively within Jupyter.
%matplotlib: any plt plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()
%matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure
%matplotlib inline: only draw static images in the notebook
Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of
IPython’s specific magic and use
matplotlib.pyplot.ion()/matplotlib.pyplot.ioff() which have the
advantages of working outside of IPython as well.
Some people use matplotlib interactively from the python shell and
have plotting windows pop up when they type commands. Some people run
Jupyter notebooks and draw inline plots for quick data analysis.
Others embed matplotlib into graphical user interfaces like wxpython
or pygtk to build rich applications. Some people use matplotlib in
batch scripts to generate postscript images from numerical
simulations, and still others run web application servers to
dynamically serve up graphs. To support all of these use cases,
matplotlib can target different outputs, and each of these
capabilities is called a backend; the “frontend” is the user facing
code, i.e., the plotting code, whereas the “backend” does all the hard
work behind-the-scenes to make the figure.
So when you type %matplotlib inline , it activates the inline backend. As discussed in the previous posts :
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.
It just means that any graph which we are creating as a part of our code will appear in the same notebook and not in separate window which would happen if we have not used this magic statement.
IPython kernel has the ability to display plots by executing code. The IPython kernel is designed to work seamlessly with the matplotlib plotting library to provide this functionality.
%matplotlib is a magic command which performs the necessary behind-the-scenes setup for IPython to work correctly hand-in-hand with matplotlib;
it does not execute any Python import commands, that is, no names are added to the namespace.
Display output in separate window
%matplotlib
Display output inline
(available only for the Jupyter Notebook and the Jupyter QtConsole)
Example – GTK3Agg – An Agg rendering to a GTK 3.x canvas (requires PyGObject and pycairo or cairocffi).
More details about matplotlib interactive backends: here
Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of
IPython’s specific magic and use matplotlib.pyplot.ion()/matplotlib.pyplot.ioff()
which have the advantages of working outside of IPython as well.
It is not mandatory to write that. It worked fine for me without (%matplotlib) magic function.
I am using Sypder compiler, one that comes with in Anaconda.
c.IPKernelApp.matplotlib=<CaselessStrEnum>Default:NoneChoices:['auto','gtk','gtk3','inline','nbagg','notebook','osx','qt','qt4','qt5','tk','wx']Configure matplotlib for interactive use with the default matplotlib backend.
I have to agree with foobarbecue (I don’t have enough recs to be able to simply insert a comment under his post):
It’s now recommended that python notebook isn’t started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.
However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.
Erronious code:
df_randNumbers1.ix[:,["A","B"]].plot.kde
Example error:
<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>
Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn’t print.
回答 9
在Jupyter的单独单元中运行绘图命令时,我遇到了同样的问题:
In[1]:%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In[2]: x = np.array([1,3,4])
y = np.array([1,5,3])In[3]: fig = plt.figure()<Figure size 432x288with0Axes>#this might be the problemIn[4]: ax = fig.add_subplot(1,1,1)In[5]: ax.scatter(x, y)Out[5]:<matplotlib.collections.PathCollection at 0x12341234># CAN'T SEE ANY PLOT :(In[6]: plt.show()# STILL CAN'T SEE IT :(
通过将绘图命令合并到单个单元格中解决了该问题:
In[1]:%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In[2]: x = np.array([1,3,4])
y = np.array([1,5,3])In[3]: fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x, y)Out[3]:<matplotlib.collections.PathCollection at 0x12341234># AND HERE APPEARS THE PLOT AS DESIRED :)
I had the same problem when I was running the plotting commands in separate cells in Jupyter:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
<Figure size 432x288 with 0 Axes> #this might be the problem
In [4]: ax = fig.add_subplot(1, 1, 1)
In [5]: ax.scatter(x, y)
Out[5]: <matplotlib.collections.PathCollection at 0x12341234> # CAN'T SEE ANY PLOT :(
In [6]: plt.show() # STILL CAN'T SEE IT :(
The problem was solved by merging the plotting commands into a single cell:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
Out[3]: <matplotlib.collections.PathCollection at 0x12341234>
# AND HERE APPEARS THE PLOT AS DESIRED :)