Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide code from cells in ipython notebook visualized with nbviewer?

People also ask

How do you minimize code cells in Jupyter Notebook?

Highlight a cell and then click on the blue bar next to it. You'll see it represented as three dots now. It will be respected when you save and reopen later or elsewhere. There is further features and options, such as View > Collapse All Code , see here and the link here.

What is %% capture in Jupyter?

Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable.

How do I use Nbviewer?

Jupyter nbviewer It is extremely simple to use. Simply paste the URL to the notebook into this web page. The notebook is now rendered via a unique link which you can share with others.


from IPython.display import HTML

HTML('''<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')

This is now possible directly from nbconvert as of version 5.2.1: content can be filtered using the built-in template exporter exclude options. For example:

jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True my_notebook.ipynb

will exclude the "input code" cells, ie the code itself. Similar options exist to exclude prompts, markdown cells, or outputs, or both inputs and outputs.

(These options should work irrespective of output format.)


I would use hide_input_all from nbextensions (https://github.com/ipython-contrib/IPython-notebook-extensions). Here's how:

  1. Find out where your IPython directory is:

    from IPython.utils.path import get_ipython_dir
    print get_ipython_dir()
    
  2. Download nbextensions and move it to the IPython directory.

  3. Edit your custom.js file somewhere in the IPython directory (mine was in profile_default/static/custom) to be similar to the custom.example.js in the nbextensions directory.

  4. Add this line to custom.js:

    IPython.load_extensions('usability/hide_input_all')
    

IPython Notebook will now have a button to toggle code cells, no matter the workbook.


I wrote some code that accomplishes this, and adds a button to toggle visibility of code.

The following goes in a code cell at the top of a notebook:

from IPython.display import display
from IPython.display import HTML
import IPython.core.display as di # Example: di.display_html('<h3>%s:</h3>' % str, raw=True)

# This line will hide code by default when the notebook is exported as HTML
di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)

# This line will add a button to toggle visibility of code blocks, for use with the HTML export version
di.display_html('''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)

You can see an example of how this looks in NBviewer here.

Update: This will have some funny behavior with Markdown cells in Jupyter, but it works fine in the HTML export version of the notebook.


The newest IPython notebook version do not allow executing javascript in markdown cells anymore, so adding a new markdown cell with the following javascript code will not work anymore to hide your code cells (refer to this link)

Change ~/.ipython/profile_default/static/custom/custom.js as below:

code_show=true;
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
}

$([IPython.events]).on("app_initialized.NotebookApp", function () {
  $("#view_menu").append("<li id=\"toggle_toolbar\" title=\"Show/Hide code cells\"><a href=\"javascript:code_toggle()\">Toggle Code Cells</a></li>")
});

This can be done using an IPython ToggleButton widget and a little bit of JavaScript. The following code should be placed into a code cell at the top of the document:

import ipywidgets as widgets
from IPython.display import display, HTML

javascript_functions = {False: "hide()", True: "show()"}
button_descriptions  = {False: "Show code", True: "Hide code"}


def toggle_code(state):

    """
    Toggles the JavaScript show()/hide() function on the div.input element.
    """

    output_string = "<script>$(\"div.input\").{}</script>"
    output_args   = (javascript_functions[state],)
    output        = output_string.format(*output_args)

    display(HTML(output))


def button_action(value):

    """
    Calls the toggle_code function and updates the button description.
    """

    state = value.new

    toggle_code(state)

    value.owner.description = button_descriptions[state]


state = False
toggle_code(state)

button = widgets.ToggleButton(state, description = button_descriptions[state])
button.observe(button_action, "value")

display(button)

This creates the following button to toggle showing/hiding the code for the Jupyter Notebook, defaulted to the "hide" state:

Hide code state

When set to the "show" state, you can then see the code for the Jupyter Notebook:

Show code state

As an aside, while much of this code should be placed at the beginning of the Notebook, the location of the toggle button is optional. Personally, I prefer to keep it at the bottom of the document. To do so, simply move the display(button) line to a separate code cell at the bottom of the page:

Relocated toggle button