How to display print statements interlaced with Matplotlib plots inline in iPython?

To display print statements interlaced with matplotlib plots inline in iPython/Jupyter notebooks, you need to combine matplotlib's inline backend with proper plot display commands. This creates a seamless output where text and plots appear in sequence.

Basic Setup

First, ensure matplotlib plots display inline in your notebook ?

import matplotlib.pyplot as plt

# Sample data for multiple histograms
data_sets = [[7, 8, 1, 3, 5], [2, 5, 2, 8, 4], [1, 9, 3, 6, 2]]

for i, data in enumerate(data_sets):
    print(f"Processing dataset {i + 1}: {data}")
    
    # Create histogram
    plt.figure(figsize=(6, 4))
    plt.hist(data, bins=5, alpha=0.7, color=f'C{i}')
    plt.title(f'Histogram of Dataset {i + 1}')
    plt.xlabel('Values')
    plt.ylabel('Frequency')
    plt.show()
    
    print(f"Mean of dataset {i + 1}: {sum(data)/len(data):.2f}")
    print("=" * 30)
Processing dataset 1: [7, 8, 1, 3, 5]
[Histogram Plot 1 displayed]
Mean of dataset 1: 4.80
==============================
Processing dataset 2: [2, 5, 2, 8, 4]
[Histogram Plot 2 displayed]
Mean of dataset 2: 4.20
==============================
Processing dataset 3: [1, 9, 3, 6, 2]
[Histogram Plot 3 displayed]
Mean of dataset 3: 4.20
==============================

Using Subplots for Better Control

For more precise control over plot positioning and text output ?

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
datasets = [
    np.random.normal(0, 1, 100),
    np.random.normal(2, 1.5, 100),
    np.random.normal(-1, 0.5, 100)
]

for i, data in enumerate(datasets):
    print(f"\n--- Analysis of Dataset {i + 1} ---")
    print(f"Data points: {len(data)}")
    print(f"Mean: {np.mean(data):.3f}")
    print(f"Standard deviation: {np.std(data):.3f}")
    
    # Create subplot
    fig, ax = plt.subplots(1, 1, figsize=(8, 5))
    ax.hist(data, bins=15, alpha=0.7, edgecolor='black')
    ax.set_title(f'Dataset {i + 1} Distribution')
    ax.set_xlabel('Values')
    ax.set_ylabel('Frequency')
    ax.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.show()
    
    print(f"Plot {i + 1} displayed above")
--- Analysis of Dataset 1 ---
Data points: 100
Mean: -0.063
Standard deviation: 1.012
[Histogram Plot displayed]
Plot 1 displayed above

--- Analysis of Dataset 2 ---
Data points: 100
Mean: 2.157
Standard deviation: 1.498
[Histogram Plot displayed]
Plot 2 displayed above

--- Analysis of Dataset 3 ---
Data points: 100
Mean: -1.024
Standard deviation: 0.487
[Histogram Plot displayed]
Plot 3 displayed above

Key Points

  • plt.show() forces immediate plot display, ensuring proper interlacing

  • Use %matplotlib inline magic command in Jupyter for inline plotting

  • Print statements appear exactly where placed in the code sequence

  • plt.figure() or plt.subplots() creates new plot instances

Alternative with Context Information

You can also add contextual information around each plot ?

import matplotlib.pyplot as plt

# Sample time series data
time_periods = ['Week 1', 'Week 2', 'Week 3']
sales_data = [[45, 52, 38, 61, 49], [38, 44, 55, 42, 48], [51, 47, 43, 58, 52]]

for period, sales in zip(time_periods, sales_data):
    print(f"\n? Sales Analysis for {period}")
    print(f"Daily sales: {sales}")
    print(f"Total sales: {sum(sales)}")
    print(f"Average daily sales: {sum(sales)/len(sales):.1f}")
    
    plt.figure(figsize=(8, 4))
    plt.bar(range(len(sales)), sales, color='skyblue', alpha=0.8)
    plt.title(f'Daily Sales - {period}')
    plt.xlabel('Day')
    plt.ylabel('Sales')
    plt.xticks(range(len(sales)), [f'Day {i+1}' for i in range(len(sales))])
    plt.show()
    
    if sum(sales) > 240:
        print("? Great performance this week!")
    else:
        print("?? Room for improvement")
? Sales Analysis for Week 1
Daily sales: [45, 52, 38, 61, 49]
Total sales: 245
Average daily sales: 49.0
[Bar Chart displayed]
? Great performance this week!

? Sales Analysis for Week 2
Daily sales: [38, 44, 55, 42, 48]
Total sales: 227
Average daily sales: 45.4
[Bar Chart displayed]
?? Room for improvement

? Sales Analysis for Week 3
Daily sales: [51, 47, 43, 58, 52]
Total sales: 251
Average daily sales: 50.2
[Bar Chart displayed]
? Great performance this week!

Conclusion

Use plt.show() after each plot to ensure immediate display and proper interlacing with print statements. This technique works best in Jupyter notebooks with the inline matplotlib backend enabled.

Updated on: 2026-03-25T19:55:27+05:30

435 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements