#!/usr/bin/env python # coding: utf-8 # ## Centered plots based on Discourse Post # [Discourse post basis](https://discourse.jupyter.org/t/center-show-a-figure/36198/2?u=fomightez) # # Developed in MyBinder-served sessions launched from [3Dscatter_plot_mod_playground-binder](https://github.com/fomightez/3Dscatter_plot_mod_playground-binder). # In[1]: import matplotlib.pyplot as plt import numpy as np import ipywidgets as widgets from IPython.display import display # Sample data x = np.linspace(0, 10, 100) y = np.sin(x) * np.exp(-x/5) # Main Matplotlib Plot fig, ax = plt.subplots(figsize=(8, 6)) ax.plot(x, y, 'b-', linewidth=2, label='sin(x) * exp(-x/5)') ax.set_xlabel('X values') ax.set_ylabel('Y values') ax.set_title('Plot Centered using ipywidgets') ax.legend() ax.grid(True, alpha=0.3) # Output widget to capture the plot output = widgets.Output() # Capture the plot in the Output widget with output: plt.show() # Clear the current figure to prevent duplicate display plt.close(fig) # Create a container to center the output # Using HBox with layout properties to center horizontally centered_container = widgets.HBox( children=[output], layout=widgets.Layout( display='flex', justify_content='center', # Center horizontally align_items='center', # Center vertically width='100%', # Full width container min_height='400px' # Minimum height for vertical centering ) ) # OPtions to Further Customize the Output widget's layout output.layout = widgets.Layout( #border='2px solid #ddd', # Add border around the plot #padding='20px', # Add padding inside the border #margin='10px', # Add margin outside the border #border_radius='10px', # Rounded corners #box_shadow='0 4px 8px rgba(0,0,0,0.1)', # Subtle shadow #background_color='#fafafa' # Light background ) display(centered_container) # In[2]: # Example of a more complex layout with title and controls def create_advanced_centered_plot(): # Create figure fig, ax = plt.subplots(figsize=(10, 6)) # Plot data x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) ax.plot(x, y, 'r-', linewidth=3) ax.set_title('Advanced Centered Layout Example') ax.set_xlabel('X') ax.set_ylabel('sin(X)') ax.grid(True) # Create output widget for the plot plot_output = widgets.Output() with plot_output: plt.show() plt.close(fig) # Title widget title_widget = widgets.HTML( value="