Interlacing Print Statements with Matplotlib Plots Inline in IPython

Rate this post

πŸ’‘ Problem Formulation: When working in an IPython environment, developers might want to display print statements alongside inline Matplotlib plots to provide additional context or data insights. This is especially useful for quick data analysis iterations within Jupyter Notebooks. The challenge arises in organising the outputs so that the print statements and plots are presented in a coherent and interpretable manner. The desired output is a seamless interweaving of narrative (print outputs) and visualizations (plots) that effectively tell the data’s story.

Method 1: Using IPython’s display with Matplotlib Inline Backend

This method involves the use of the IPython core display module which provides API for displaying objects in different formats. By default, IPython notebook uses the ‘inline’ backend that results in Matplotlib plots being displayed under the code cell that produced them.

Here’s an example:

from IPython.display import display
import matplotlib.pyplot as plt

print("Displaying plot A:")
plt.figure()
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()

print("Displaying plot B:")
plt.figure()
plt.plot([1, 2, 3], [1, 2, 3])
plt.show()

This would output the text “Displaying plot A:” followed by the first plot, then “Displaying plot B:” followed by the second plot, all inline with the IPython notebook cell outputs.

Method 2: Saving Figures and Displaying with IPython Image

Another method to control the display of print statements and plots is to save the plots as images and then display them alongside the print statements using IPython’s Image display object. This can preserve the quality and layout of each plot.

Here’s an example:

from IPython.display import Image, display
import matplotlib.pyplot as plt

plt.figure()
plt.plot([1, 2, 3], [1, 4, 9])
plt.savefig('plot_a.png')
display(Image(filename='plot_a.png'))

print("Plot A displayed above.")

plt.figure()
plt.plot([1, 2, 3], [1, 2, 3])
plt.savefig('plot_b.png')
display(Image(filename='plot_b.png'))

print("Plot B displayed above.")

This method saves the plots as images then displays them using Image, with the print statements providing context underneath each plot.

Method 3: Inline Magic with Print Statements

The IPython magic command %matplotlib inline can be used to set up inline plotting where the plots will be displayed directly below the code cell that produced it. Combined with print statements this allows for seamless integration.

Here’s an example:

%matplotlib inline
import matplotlib.pyplot as plt

print("Plot C will be displayed inline.")
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()

This approach allows the plots to be rendered inline automatically after the print statement “Plot C will be displayed inline.” is executed.

Method 4: Sequencing Displays within IPython Cells

By carefully sequencing print statements and plot display commands, one can achieve a manual interleaving of text and visuals within a single IPython cell.

Here’s an example:

import matplotlib.pyplot as plt

print("Starting sequence:")
# Generate first plot
print("Plot D:")
plt.figure()
plt.plot([1, 2, 3], [1, 2, 1])
plt.show()

# Following print statement
print("Just displayed Plot D.")

The execution of plot commands and print statements are sequenced manually. This gives the user full control over when and how each piece of output is displayed in relation to each other.

Bonus One-Liner Method 5: Combining Prints and Plots as Subplots

For a compact solution, you can create subplots and use the title or text annotations to include the print statements directly on the plot, albeit not as flexible as the previous methods.

Here’s an example:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2)
axs[0].plot([1, 2, 3], [1, 4, 9])
axs[0].set_title('Printed Statement: Plot 1 Characteristics')
axs[1].plot([1, 2, 3], [1, 2, 1])
axs[1].text(1, 1, 'Printed Statement: Plot 2 Analysis')
plt.show()

This creates two subplots with an embedded title and text annotation that serves as inline comments or print statements, all within the plot area.

Summary/Discussion

  • Method 1: Using IPython’s display. Strengths: Easy to use, inline with IPython’s output stream. Weaknesses: Less control over plot display timings.
  • Method 2: Saving Figures and Displaying with IPython Image. Strengths: Preserves the layout and quality of images. Weaknesses: Additional overhead for saving and loading images.
  • Method 3: Inline Magic with Print Statements. Strengths: Simplifies the plotting process, good for quick visual assessments. Weaknesses: Limited control over more complex plotting scenarios.
  • Method 4: Sequencing Displays within IPython Cells. Strengths: High level of control over output sequence. Weaknesses: Can become unruly with complex outputs.
  • Method 5: Combining Prints and Plots as Subplots. Strengths: Neat, consolidated output. Weaknesses: Limited flexibility, and print statements become part of the plot, which may not be desirable.