How to Hide Code in a Jupyter Notebook: Clean Presentations and Focused Insights

Jupyter Notebooks are fantastic for data analysis, visualization, and sharing your work. But sometimes, you want to present your findings without overwhelming your audience with the underlying code. Perhaps you’re creating a report, giving a presentation, or sharing a notebook with non-technical colleagues. Showing every single line of code can be distracting and detract from the story you’re trying to tell.

The good news is, Jupyter Notebook offers several ways to selectively hide code, allowing you to showcase only the essential results, visualizations, and narrative. This guide explores the most effective techniques for creating clean, presentation-ready notebooks that emphasize insights over implementation. We’ll cover everything from simple cell hiding to more advanced customization options, empowering you to craft compelling and focused data stories.

Why Hide Code in Jupyter Notebooks?

Before diving into the how, let’s consider the why. Hiding code serves several vital purposes:

  • Improved Readability: Removes clutter and allows readers to focus on the output and narrative.
  • Enhanced Presentations: Creates a cleaner and more professional look for presentations and reports.
  • Targeted Communication: Allows you to tailor the level of detail to your audience’s technical expertise.
  • Focus on Insights: Emphasizes the results and conclusions rather than the implementation details.
  • Simplified Collaboration: Makes notebooks easier to understand and collaborate on, especially with non-programmers.

Ultimately, hiding code is about effective communication. It’s about presenting your work in the most digestible and impactful way possible.

Basic Techniques for Hiding Code Cells

Let’s start with the simplest methods for hiding code cells. These techniques are built directly into Jupyter Notebook and require minimal setup.

1. Collapsing Cells Manually

The most straightforward approach is to collapse individual cells manually. In the Jupyter Notebook interface, you’ll see a small arrow next to each code cell. Clicking this arrow collapses the cell, hiding the code while preserving the output.

Pros:

  • Simple and quick for occasional use.
  • Easy to control which cells are hidden.

Cons:

  • Manual process, which can be tedious for large notebooks.
  • The collapsed state isn’t saved with the notebook, meaning it’s forgotten when you reopen the file.

2. Using the ‘Toggle Code’ Extension (Nbextensions)

Nbextensions is a collection of incredibly useful extensions that enhance the functionality of Jupyter Notebook. One of these extensions, Toggle Code, allows you to add a button to each code cell that toggles its visibility. This is a significant improvement over manual collapsing as the setting *issaved with the notebook.

How to install and enable Nbextensions:

  1. Install: Open your terminal or Anaconda Prompt and run: pip install jupyter_contrib_nbextensions
  2. Install Javascript and CSS files: jupyter contrib nbextension install --user
  3. Enable: Restart your Jupyter Notebook server. A new tab called Nbextensions should appear. Check the box next to Toggle code to enable the extension.

Once enabled, a “Toggle Code” button will appear for each code cell. Clicking it will hide or show the code, and this state is saved with the notebook. This is a convenient way to manage code visibility on a cell-by-cell basis.

Pros:

  • Persistent hiding: the hidden state is saved with the notebook.
  • Easy to toggle code visibility with a single click.

Cons:

  • Requires installing and configuring Nbextensions.
  • Still a manual process, although more efficient than manual collapsing.

Advanced Techniques with IPython.display and HTML

For more control and customization, you can use IPython.display and HTML to hide code cells. This involves embedding HTML within your notebook to create toggles or hide elements based on specific conditions.

1. Creating a Toggle Button with HTML and Javascript

This method involves adding a small snippet of HTML and Javascript code to your notebook. This code creates a button that, when clicked, toggles the visibility of a specific code cell.

Steps:

  1. Insert an HTML code block: Create a new code cell and enter the following HTML (use from IPython.display import HTML first if needed):

<button onclick=
var code = $(this).closest('div.input');
code.toggle('slow');
>Toggle Code</button>
  1. Execute the cell: Run the code cell. This will create a Toggle Code button above the *nextcell.
  2. (Optional) Style the button: You can customize the button’s appearance using CSS within the HTML code.

Explanation:

  • The <button> tag creates a button.
  • The onclick attribute specifies the JavaScript code to run when the button is clicked.
  • $(this).closest('div.input') selects the closest parent div element with the class input (which represents the code cell).
  • .toggle('slow') toggles the visibility of the selected element with a slow animation.

Pros:

  • More control over the appearance and behavior of the toggle.
  • No dependency on external extensions (only requires IPython).

Cons:

  • Requires writing HTML and Javascript code.
  • Must be repeated for each code cell you want to hide (unless you use a loop to generate the code).

2. Hiding all Input Cells by Default

You might want to hide all code cells by default and only reveal them when needed. This can be achieved with a bit more HTML and some CSS styling injected into the notebook.

Steps:

  1. Insert an HTML/CSS code block: Create a new code cell at the *beginningof your notebook and enter the following code (use from IPython.display import HTML first if needed):

<style>
div.input {
    display: none;
}
</style>
<button onclick=
var code = document.querySelectorAll('div.input');
for (var i = 0; i < code.length; i++){
    code[i].style.display = code[i].style.display === 'none' ? 'block' : 'none';
}
>Toggle All Code</button>
  1. Execute the cell: Run the code cell. The code cells will disappear but the output will remain.

Explanation:

  • The <style> tag includes CSS code that hides all div elements with the class input (i.e., all code cells).
  • The javascript loops through all input cells and toggles the display property between ‘none’ and ‘block’.

Related image

Pros:

  • Hides all code cells by default with a single code block.
  • Creates a clean and uncluttered view.

Cons:

  • Hides *allinput cells.
  • Requires HTML and Javascript knowledge for complete customisation.

Using RISE for Presentations

RISE (Reveal.js – Jupyter/IPython Slideshow Extension) is a powerful tool for creating interactive presentations from Jupyter Notebooks. It allows you to convert your notebook into a slideshow with a few simple tags, and offers built-in support for hiding code cells.

How to install and use RISE:

  1. Install: Open your terminal or Anaconda Prompt and run: pip install rise
  2. Enable: Restart your Jupyter Notebook server. A Slideshow button will appear in the toolbar.
  3. Assign Slide Types: For each cell, use the Cell Toolbar (View -> Cell Toolbar -> Slideshow) to assign a slide type (e.g., Slide, Sub-slide, Fragment).
  4. Start the presentation: Click the Slideshow button to start the presentation.

Hiding Code in RISE:

RISE automatically hides code cells by default when you start a presentation. To show the code for a specific cell, you need to explicitly mark it as visible.

  1. In the metadata, you can modify the cell’s metadata to show the cell’s input:

{
  cell_type: code,
  execution_count: null,
  metadata: {
    slideshow: {
      hide_code: false
    }
  },
  outputs: [],
  source: []
}
  1. Alternatively, you can enable the ‘Edit Notebook Metadata’ extension, allowing easy access to modify the metadata for any given cell . Navigate to Nbextensions tab, check the Edit Notebook Metadata box and restart your notebook.

Pros:

  • Creates professional-looking presentations directly from Jupyter Notebooks.
  • Easy to hide code cells by default.
  • Supports interactive elements and visualizations.

Cons:

  • Requires learning how to use RISE and its slideshow features.
  • May require some customization to achieve the desired presentation style.

Choosing the Right Technique

The best method for hiding code in a Jupyter Notebook depends on your specific needs and goals.

  • For quick and occasional cell hiding: Use the manual collapsing feature.
  • For persistent cell hiding and easy toggling: Use the Toggle Code Nbextension.
  • For customized toggle buttons and more control: Use HTML and Javascript.
  • For hiding all code cells by default: Use the HTML/CSS approach.
  • For creating presentations: Use RISE.

Experiment with different techniques to find the one that best suits your workflow and presentation style.

Best Practices for Clear and Concise Notebooks

Regardless of the method you choose for hiding code, consider these best practices:

  • Write clear and concise code: This makes it easier to understand even when it’s hidden.
  • Add comments to explain your code: Comments provide context and make your code more maintainable.
  • Use markdown cells to provide explanations and context: Markdown cells are essential for telling the story behind your data and code.
  • Focus on the results and insights: Emphasize the conclusions and implications of your work.
  • Test your notebook with different audiences: Get feedback from others to ensure your notebook is clear and understandable.

Conclusion

Hiding code in Jupyter Notebooks is a powerful technique for creating cleaner, more focused, and more impactful presentations. By selectively hiding code cells, you can emphasize the results, insights, and narrative of your work, making it easier for your audience to understand and appreciate your findings. Whether you choose simple manual collapsing, the convenience of Nbextensions, the customization of HTML/Javascript, or the presentation power of RISE, mastering these techniques will significantly enhance your Jupyter Notebook skills and communication abilities. So go forth and create notebooks that shine!