collapse cell in jupyter notebook - python
I am using ipython Jupyter notebook. Let's say I defined a function that occupies a lot of space on my screen. Is there a way to collapse the cell?
I want the function to remain executed and callable, yet I want to hide / collapse the cell in order to better visualize the notebook. How can I do this?
UPDATE:
The newer jupyter-lab is a more modern and feature-rich interface which supports cell folding by default. See #intsco's answer below
UPDATE 2
Since jupyter-lab now also supports extensions, you can extend the built-in cell-folding functionality with the Collapsible_Headings extension.
Original answer:
The jupyter contrib nbextensions Python package contains a code-folding extension that can be enabled within the notebook. Follow the link (Github) for documentation.
To install using command line:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
To make life easier in managing them, I'd also recommend the jupyter nbextensions configurator package. This provides an extra tab in your Notebook interface from where you can easily (de)activate all installed extensions.
Installation:
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user
JupyterLab supports cell collapsing. Clicking on the blue cell bar on the left will fold the cell.
You can create a cell and put the following code in it:
%%html
<style>
div.input {
display:none;
}
</style>
Running this cell will hide all input cells. To show them back, you can use the menu to clear all outputs.
Otherwise you can try notebook extensions like below:
https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/Home_3x
I had a similar issue and the "nbextensions" pointed out by #Energya worked very well and effortlessly. The install instructions are straight forward (I tried with anaconda on Windows) for the notebook extensions and for their configurator.
That said, I would like to add that the following extensions should be of interest.
Hide Input |
This extension allows hiding of an individual codecell in a notebook. This can be achieved by clicking on the toolbar button:
Collapsible Headings | Allows notebook to have collapsible sections, separated by headings
Codefolding | This has been mentioned but I add it for completeness
There are many answers to this question, all of which I feel are not satisfactory (some more than others), of the many extensions - code folding, folding by headings etc etc. None do what I want in simple and effective way. I am literally amazed that a solution has not been implemented (as it has for Jupyter Lab).
In fact, I was so dissatisfied that I have developed a very simple notebook extension that can expand/collapse the code in a notebook cell, while keeping it executable.
The GitHub repository: https://github.com/BenedictWilkinsAI/cellfolding
Below is a small demo of what the extension does:
Simply double clicking left of the code cell will collapse it to a single line:
Double clicking again will expand the cell.
The extension can be installed easily with pip:
pip install nbextension-cellfolding
jupyter nbextension install --py cellfolding --user
jupyter nbextension enable --py cellfolding --user
and is also compatible with nbextension configurator. I hope that people will find this useful!
Create custom.js file inside ~/.jupyter/custom/ with following contents:
$("<style type='text/css'> .cell.code_cell.collapse { max-height:30px; overflow:hidden;} </style>").appendTo("head");
$('.prompt.input_prompt').on('click', function(event) {
console.log("CLICKED", arguments)
var c = $(event.target.closest('.cell.code_cell'))
if(c.hasClass('collapse')) {
c.removeClass('collapse');
} else {
c.addClass('collapse');
}
});
After saving, restart the server and refresh the notebook. You can collapse any cell by clicking on the input label (In[]).
The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as
pip3 install hide_code
Visit https://github.com/kirbs-/hide_code/ for more info about this extension.
Firstly, follow Energya's instruction:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user
Second is the key: After opening jupiter notebook, click the Nbextension tab. Now Search "colla" from the searching tool provided by Nbextension(not by the web browser), then you will find something called "Collapsible Headings"
This is what you want!
As others have mentioned, you can do this via nbextensions. I wanted to give the brief explanation of what I did, which was quick and easy:
To enable collabsible headings:
In your terminal, enable/install Jupyter Notebook Extensions by first entering:
pip install jupyter_contrib_nbextensions
Then, enter:
jupyter contrib nbextension install
Re-open Jupyter Notebook. Go to "Edit" tab, and select "nbextensions config".
Un-check box directly under title "Configurable nbextensions", then select "collapsible headings".
There's also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:
%%html
<style id=hide>div.input{display:none;}</style>
<button type="button"
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>
Or python:
# Run me to hide code cells
from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))
You don't need to do much except to enable the extensions:
http://localhost:8888/nbextensions?nbextension=collapsible_headings
http://localhost:8888/nbextensions?nbextension=codefolding/main
Most probable you will find all your extensions in here:
http://localhost:8888/nbextensions
What I use to get the desired outcome is:
Save the below code block in a file named toggle_cell.py in the same directory as of your notebook
from IPython.core.display import display, HTML
toggle_code_str = '''
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Sloution"></form>
'''
toggle_code_prepare_str = '''
<script>
function code_toggle() {
if ($('div.cell.code_cell.rendered.selected div.input').css('display')!='none'){
$('div.cell.code_cell.rendered.selected div.input').hide();
} else {
$('div.cell.code_cell.rendered.selected div.input').show();
}
}
</script>
'''
display(HTML(toggle_code_prepare_str + toggle_code_str))
def hide_sloution():
display(HTML(toggle_code_str))
Add the following in the first cell of your notebook
from toggle_cell import toggle_code as hide_sloution
Any cell you need to add the toggle button to simply call hide_sloution()
I had the same problem, I found this extension useful
pip install aquirdturtle_collapsible_headings
Related
Jupyter Notebook: Autocomplete has too many suggestions
When using autocomplete in Jupyter Notebooks it is super nice that you can use autocomplete out of the box, but the autocomplete makes too many suggestions that are not relevant. E.g. when autocompleting inside a function, then I only want relevant parameters to be autocompleted, not 60 random python values. People have suggested using %config Completer.use_jedi = True, but that turns everything off and is even worse.
You can try installing nbextension for suggestions in jupyter notebook. for more info plz Click here
Hiding and showing sections in Jupyter notebook
I am using jupyter notebook on my PC. As the length of my codes is increasing, I want to hide and display some sections of the python code based on the heading markings in Jupyter Notebook like the google colab does. Is there any python package to install in the environment specifically for this functionality? Similar to the screenshots below. Hidden Codes based on the headings [1]: https://i.stack.imgur.com/kQSMG.png Expanded Python Codes [2]: https://i.stack.imgur.com/20HNw.png
Error loading preloads: Could not find renderer
I am running jupyter notebook in vscode. But when I try to run the following cell of code I got error. import os from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder import torchvision.transforms as tt import torch import torch.nn as nn import cv2 from tqdm.notebook import tqdm import torch.nn.functional as F from torchvision.utils import save_image from torchvision.utils import make_grid import matplotlib.pyplot as plt %matplotlib inline The error is Error loading preloads: Could not find renderer I tried but could not find its solution on the internet. How can I resolve this issue?
In my case, I had Jupyter notebook extension installed. So, I did ctrl+shift+P and did Reload window; resolved! In case you just don't see the bar without any error: disable Jupyter notebook renderers extension, test, and then re-enable it
I am having the same issue with the latest release of the VS code Jupyer extension. The fix for now is to just go to the Jupyter extension tab, then the button that says "Uninstall," click the down arrow and hit "Install Another Version" and just install the version from > 1 mo ago and it should work fine. Hopefully they'll resolve this issue in the latest version soon.
Install/reinstall Jupyter Notebook Renderers Extension Reload Window Open the Command Palette (Ctrl + Shift + P) Then type: Reload Window If this still doesn't work, make sure plot presentation is set to: image/png Jupyter Notebook Renderer (ms-toolsai.jupyter-renderers) Change Presentation Select Renderer You should now be able to generate a plot in the interactive window. Hovering over the plot will give options to expand or save. To get a better looking plot when zoomed in enable the "Jupyter: Generate SVGPlots" setting in the "Jupyter" extension and reload the window again. Then change the plot presentation to: image/svg+xml Jupyter Notebook Renderer (ms-toolsai.jupyter-renderers)
From the github issue: Renderer extension not being installed -- causes some packages not to work, like plotly. It should have been fixed in new release because the issue was closed on 14 Jan. Run this code and see if the question goes away: import plotly.io as pio pio.renderers.default = 'iframe_connected' OR You may try to uninstall Jupyter extension completely by deleting its packages in the folder \...\.vscode\extensions\ms-toolsai.jupyter then reinstall the latest version.
Install extension Jupyter Notebook Renderers and update your VS code to the latest version.
just disable the "jupyter notebook renderers" in the extension section and then Reload it. Lastly, enable it and you're good to go.
When you install the Jupyter extension, Jupyter Notebook Renderers are also installed because it's included in the extension pack. This extension is causing this error so remove the extension from the Jupyter extension details and try running the block again.
If the mentioned solutions do not work try the followings as well: check if you have all packages installed, for me the problem was that one package was not installed and I saw the same error as you mentioned which is totally irrelevant to missing one package! if that does not work either, simply check if you are using the correct Python interpreter in the correct environment.
As for me, this happened because of the "Workspace Trust" thing, where normally you would open the file/files by right-clicking the folder from explorer and click "Open with VSCode". Instead, i opened the notebook's file directly with VSCode and the Workspace Trust tab shows up. The Workspace Trust makes almost all of your extension disabled, including the Jupyter's ones. Normally, you can just trust your workspace/directory in the same session and your extensions will be reloaded without needing of restart, apparently this is not the case as the problem appeared and only disappeared after a VSCode restart. So, TL;DR : Workspace Trust tab shows up > Trust the workspace > restart VSCode
I think you should try restarting VSCode.
Just uninstall Jupyter Notebook Extension in VScode Extension, Reload the VScode window then install back Jupyter Notebook extension and run the cells again. It sloved my problem
Produce HTML output from AWS EMR Jupyter Notebook
I'm currently running a default/basic notebook on EMR (Release label: emr-6.1.0, Applications: Spark 3.0.0, Zeppelin 0.9.0, JupyterHub 1.1.0) and i'm having some issues getting the notebook to output a data profiling report in HTML. I've installed pandas-profiling a variety of ways, using custom bootstrap actions & with the command sc.install_pypi_package("pandas-profiling") I run into the following issue after trying to generate the report's HTML using IPython. It only produces the object vs the HTML. I'm also aware that adding %%local can help produce it, like below. But installing through bootstrap actions/on the notebook does not install from wherever %%local is located. As seen below. So my first question is, can this profile report be produced without the %%local magic? I know there is also an %%html magic command, but that cannot print out a variable based on my testing, hence why I need IPython. Second question is, how can pandas-profiling be added to this %%local environment? Should this even be the approach? Thanks!!
Is there a document map extension for Jupyter notebook?
One of the main advantages of using Jupyter is the ability to code and document in the same time. Many times, I use headings and subheadings to group the code in a notebook. However, as the notebook gets longer, navigation becomes much harder. It would be nice to have a document map in a separate (left) pane that keeps track of the markdown headings. Once a heading is selected in the document map, the respective section would appear in the main pane. Is there an extension for this task?
I cannot comment on your question (low points) so if the answer is a bit off... I've found an extension that looks like what you need src: https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tree/master/src/jupyter_contrib_nbextensions/nbextensions/toc2 Documentation: http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/toc2/README.html Another, not that good: (imho) https://github.com/captainsafia/notebook-toc Possible duplicate of: How can I add a table of contents to an ipython notebook? EDIT Install instructions: Toc2 is included in: https://github.com/ipython-contrib/jupyter_contrib_nbextensions to install just TOC2 i did this: pip3 install jupyter_contrib_nbextensions jupyter contrib nbextension install --user jupyter nbextension enable toc2/main EDIT 2 How to display the TOC inside a notebook: http://awesomescreenshot.com/0116cqvh5b