Diverse Output Types Demo¶
This notebook showcases various output types that MkDocs-Jupyter can handle, demonstrating the full range of Jupyter's rich output capabilities.
1. MIME Type Outputs¶
Jupyter supports multiple MIME types for rich content display:
In [ ]:
Copied!
from IPython.display import HTML, JSON, Javascript, Latex, Markdown, display
# Markdown output
display(
Markdown(
"""
### Markdown Output
This is **bold** and this is *italic*.
- List item 1
- List item 2
- Nested item
[This is a link](https://www.mkdocs.org)
"""
)
)
from IPython.display import HTML, JSON, Javascript, Latex, Markdown, display
# Markdown output
display(
Markdown(
"""
### Markdown Output
This is **bold** and this is *italic*.
- List item 1
- List item 2
- Nested item
[This is a link](https://www.mkdocs.org)
"""
)
)
In [ ]:
Copied!
# LaTeX output
display(
Latex(
r"""
\begin{align}
E &= mc^2 \\
F &= ma \\
\nabla \cdot \mathbf{E} &= \frac{\rho}{\epsilon_0}
\end{align}
"""
)
)
# LaTeX output
display(
Latex(
r"""
\begin{align}
E &= mc^2 \\
F &= ma \\
\nabla \cdot \mathbf{E} &= \frac{\rho}{\epsilon_0}
\end{align}
"""
)
)
In [ ]:
Copied!
# JSON output with syntax highlighting
data = {
"name": "MkDocs-Jupyter",
"features": ["Execute notebooks", "Preserve outputs", "Handle errors"],
"configuration": {"execute": True, "allow_errors": True, "theme": "dark"},
}
display(JSON(data))
# JSON output with syntax highlighting
data = {
"name": "MkDocs-Jupyter",
"features": ["Execute notebooks", "Preserve outputs", "Handle errors"],
"configuration": {"execute": True, "allow_errors": True, "theme": "dark"},
}
display(JSON(data))
2. Image Outputs¶
Various ways to display images:
In [ ]:
Copied!
import base64
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import SVG, Image
# Generate a simple plot and display as image
fig, ax = plt.subplots(figsize=(6, 4))
x = np.linspace(0, 2 * np.pi, 100)
ax.plot(x, np.sin(x), "b-", label="sin(x)")
ax.plot(x, np.cos(x), "r-", label="cos(x)")
ax.set_title("Inline Plot Display")
ax.legend()
ax.grid(True, alpha=0.3)
# Save to buffer and display
buffer = BytesIO()
plt.savefig(buffer, format="png", dpi=150, bbox_inches="tight")
plt.close()
buffer.seek(0)
img_data = buffer.read()
display(Image(img_data))
import base64
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import SVG, Image
# Generate a simple plot and display as image
fig, ax = plt.subplots(figsize=(6, 4))
x = np.linspace(0, 2 * np.pi, 100)
ax.plot(x, np.sin(x), "b-", label="sin(x)")
ax.plot(x, np.cos(x), "r-", label="cos(x)")
ax.set_title("Inline Plot Display")
ax.legend()
ax.grid(True, alpha=0.3)
# Save to buffer and display
buffer = BytesIO()
plt.savefig(buffer, format="png", dpi=150, bbox_inches="tight")
plt.close()
buffer.seek(0)
img_data = buffer.read()
display(Image(img_data))
In [ ]:
Copied!
# SVG output
svg_content = """
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="80" fill="#4CAF50" opacity="0.7"/>
<rect x="50" y="50" width="100" height="100" fill="#2196F3" opacity="0.7"/>
<text x="100" y="100" text-anchor="middle" fill="white" font-size="20" font-weight="bold">SVG</text>
</svg>
"""
display(SVG(svg_content))
# SVG output
svg_content = """
"""
display(SVG(svg_content))
3. DataFrame and Table Outputs¶
Different ways to display tabular data:
In [ ]:
Copied!
import pandas as pd
# Create sample DataFrame
df = pd.DataFrame(
{
"Output Type": ["Text", "HTML", "Image", "Plot", "DataFrame", "Error"],
"Support": ["✓", "✓", "✓", "✓", "✓", "✓"],
"Quality": ["Excellent", "Excellent", "Good", "Good", "Excellent", "Good"],
"Notes": [
"All text preserved",
"Full HTML support",
"PNG/JPEG/SVG",
"Matplotlib/Seaborn",
"Styled tables",
"Traceback formatting",
],
}
)
# Display with styling
styled_df = df.style.set_properties(
**{"background-color": "#f0f0f0", "color": "black", "border": "1px solid #ddd"}
).set_table_styles(
[{"selector": "th", "props": [("background-color", "#4CAF50"), ("color", "white")]}]
)
styled_df
import pandas as pd
# Create sample DataFrame
df = pd.DataFrame(
{
"Output Type": ["Text", "HTML", "Image", "Plot", "DataFrame", "Error"],
"Support": ["✓", "✓", "✓", "✓", "✓", "✓"],
"Quality": ["Excellent", "Excellent", "Good", "Good", "Excellent", "Good"],
"Notes": [
"All text preserved",
"Full HTML support",
"PNG/JPEG/SVG",
"Matplotlib/Seaborn",
"Styled tables",
"Traceback formatting",
],
}
)
# Display with styling
styled_df = df.style.set_properties(
**{"background-color": "#f0f0f0", "color": "black", "border": "1px solid #ddd"}
).set_table_styles(
[{"selector": "th", "props": [("background-color", "#4CAF50"), ("color", "white")]}]
)
styled_df
In [ ]:
Copied!
# Display summary statistics
data = pd.DataFrame(
{
"A": np.random.normal(100, 15, 100),
"B": np.random.normal(50, 10, 100),
"C": np.random.normal(75, 20, 100),
}
)
print("Summary Statistics:")
data.describe().round(2)
# Display summary statistics
data = pd.DataFrame(
{
"A": np.random.normal(100, 15, 100),
"B": np.random.normal(50, 10, 100),
"C": np.random.normal(75, 20, 100),
}
)
print("Summary Statistics:")
data.describe().round(2)
4. Interactive Widgets (Static Representation)¶
While full interactivity may be limited, widget states are preserved:
In [ ]:
Copied!
# Simulate widget output
from IPython.display import HTML, display
widget_html = """
<div style="border: 2px solid #ddd; padding: 10px; border-radius: 5px; background-color: #f9f9f9;">
<h4>Interactive Widget (Static View)</h4>
<label>Slider Value: </label>
<input type="range" min="0" max="100" value="50" style="width: 200px;" disabled>
<span>50</span>
<br><br>
<label>Dropdown: </label>
<select disabled>
<option>Option A</option>
<option selected>Option B</option>
<option>Option C</option>
</select>
<br><br>
<button style="background-color: #4CAF50; color: white; padding: 5px 10px; border: none; border-radius: 3px;" disabled>
Execute (Disabled in static view)
</button>
</div>
"""
display(HTML(widget_html))
# Simulate widget output
from IPython.display import HTML, display
widget_html = """
"""
display(HTML(widget_html))
Interactive Widget (Static View)
505. Progress Bars and Animation¶
Progress indicators are captured at their final state:
In [ ]:
Copied!
import time
from IPython.display import clear_output
# Simple progress bar simulation
def progress_bar(total=100):
for i in range(total + 1):
progress = i / total
bar_length = 40
filled_length = int(bar_length * progress)
bar = "█" * filled_length + "░" * (bar_length - filled_length)
print(f"\rProgress: |{bar}| {progress*100:.1f}% Complete", end="", flush=True)
if i < total:
time.sleep(0.01)
print() # New line after completion
print("Processing data...")
progress_bar(100)
print("Processing complete!")
import time
from IPython.display import clear_output
# Simple progress bar simulation
def progress_bar(total=100):
for i in range(total + 1):
progress = i / total
bar_length = 40
filled_length = int(bar_length * progress)
bar = "█" * filled_length + "░" * (bar_length - filled_length)
print(f"\rProgress: |{bar}| {progress*100:.1f}% Complete", end="", flush=True)
if i < total:
time.sleep(0.01)
print() # New line after completion
print("Processing data...")
progress_bar(100)
print("Processing complete!")
6. Code Syntax Highlighting¶
Code blocks with syntax highlighting:
In [ ]:
Copied!
from IPython.display import HTML
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import JavascriptLexer, PythonLexer
# Python code example
python_code = '''
def fibonacci(n):
"""Generate Fibonacci sequence up to n terms"""
a, b = 0, 1
result = []
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
# Generate first 10 Fibonacci numbers
fib_sequence = fibonacci(10)
print(f"Fibonacci sequence: {fib_sequence}")
'''
# Highlight the code
formatter = HtmlFormatter(style="colorful")
highlighted = highlight(python_code, PythonLexer(), formatter)
# Display with custom styling
html_output = f"""
<style>
{formatter.get_style_defs('.highlight')}
.highlight {{ background: #f8f8f8; padding: 10px; border-radius: 5px; }}
</style>
<div class="highlight">
{highlighted}
</div>
"""
display(HTML(html_output))
from IPython.display import HTML
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import JavascriptLexer, PythonLexer
# Python code example
python_code = '''
def fibonacci(n):
"""Generate Fibonacci sequence up to n terms"""
a, b = 0, 1
result = []
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
# Generate first 10 Fibonacci numbers
fib_sequence = fibonacci(10)
print(f"Fibonacci sequence: {fib_sequence}")
'''
# Highlight the code
formatter = HtmlFormatter(style="colorful")
highlighted = highlight(python_code, PythonLexer(), formatter)
# Display with custom styling
html_output = f"""
{highlighted}
"""
display(HTML(html_output))7. Multiple Output Formats¶
Demonstrating multiple representations of the same data:
In [ ]:
Copied!
# Create data
categories = ["Python", "R", "Julia", "JavaScript"]
values = [85, 70, 60, 75]
# 1. Text representation
print("1. Text Output:")
for cat, val in zip(categories, values):
print(f" {cat}: {'*' * (val // 5)}")
# 2. DataFrame representation
print("\n2. DataFrame Output:")
df = pd.DataFrame({"Language": categories, "Usage %": values})
display(df)
# 3. Plot representation
print("\n3. Visual Output:")
fig, ax = plt.subplots(figsize=(8, 4))
colors = ["#3776ab", "#276DC3", "#9558B2", "#F7DF1E"]
bars = ax.bar(categories, values, color=colors)
ax.set_ylabel("Usage %")
ax.set_title("Language Usage in Data Science")
ax.set_ylim(0, 100)
# Add value labels
for bar, val in zip(bars, values):
ax.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 1,
f"{val}%",
ha="center",
va="bottom",
)
plt.tight_layout()
plt.show()
# 4. HTML representation
print("\n4. HTML Output:")
html_bars = """
<div style="width: 100%; max-width: 400px;">
"""
for cat, val, color in zip(categories, values, colors):
html_bars += f"""
<div style="margin: 5px 0;">
<span style="display: inline-block; width: 80px;">{cat}:</span>
<div style="display: inline-block; width: {val*2}px; height: 20px;
background-color: {color}; vertical-align: middle;"></div>
<span style="margin-left: 5px;">{val}%</span>
</div>
"""
html_bars += "</div>"
display(HTML(html_bars))
# Create data
categories = ["Python", "R", "Julia", "JavaScript"]
values = [85, 70, 60, 75]
# 1. Text representation
print("1. Text Output:")
for cat, val in zip(categories, values):
print(f" {cat}: {'*' * (val // 5)}")
# 2. DataFrame representation
print("\n2. DataFrame Output:")
df = pd.DataFrame({"Language": categories, "Usage %": values})
display(df)
# 3. Plot representation
print("\n3. Visual Output:")
fig, ax = plt.subplots(figsize=(8, 4))
colors = ["#3776ab", "#276DC3", "#9558B2", "#F7DF1E"]
bars = ax.bar(categories, values, color=colors)
ax.set_ylabel("Usage %")
ax.set_title("Language Usage in Data Science")
ax.set_ylim(0, 100)
# Add value labels
for bar, val in zip(bars, values):
ax.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 1,
f"{val}%",
ha="center",
va="bottom",
)
plt.tight_layout()
plt.show()
# 4. HTML representation
print("\n4. HTML Output:")
html_bars = """
"""
for cat, val, color in zip(categories, values, colors):
html_bars += f"""
"
display(HTML(html_bars))
{cat}:
{val}%
"""
html_bars += "Summary¶
This notebook demonstrated:
- MIME type outputs: Markdown, LaTeX, JSON, HTML
- Image outputs: PNG, SVG, matplotlib plots
- Tabular data: DataFrames with styling
- Interactive widgets: Static representation
- Progress indicators: Final state capture
- Syntax highlighting: Code with colors
- Multiple formats: Same data in different views
All these output types are preserved when building documentation with MkDocs-Jupyter!