Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fomightez/704dedc34593c20dfbd115ac3c3e34c7 to your computer and use it in GitHub Desktop.
Save fomightez/704dedc34593c20dfbd115ac3c3e34c7 to your computer and use it in GitHub Desktop.
Centered MAtplotlib plots based on Discourse Post
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "056eb2c7-3b5d-46d6-9dbf-4cc5fd23af3b",
"metadata": {},
"source": [
"## Centered plots based on Discourse Post\n",
"[Discourse post basis](https://discourse.jupyter.org/t/center-show-a-figure/36198/2?u=fomightez)\n",
"\n",
"Developed in MyBinder-served sessions launched from [3Dscatter_plot_mod_playground-binder](https://github.com/fomightez/3Dscatter_plot_mod_playground-binder)."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "5c7eb094-de26-4b86-8725-5dca3b8b0abd",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "a6bdad772e534dee8e7c12d4f18c4790",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"HBox(children=(Output(),), layout=Layout(align_items='center', display='flex', justify_content='center', min_h…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import ipywidgets as widgets\n",
"from IPython.display import display\n",
"\n",
"# Sample data\n",
"x = np.linspace(0, 10, 100)\n",
"y = np.sin(x) * np.exp(-x/5)\n",
"\n",
"# Main Matplotlib Plot\n",
"fig, ax = plt.subplots(figsize=(8, 6))\n",
"ax.plot(x, y, 'b-', linewidth=2, label='sin(x) * exp(-x/5)')\n",
"ax.set_xlabel('X values')\n",
"ax.set_ylabel('Y values')\n",
"ax.set_title('Plot Centered using ipywidgets')\n",
"ax.legend()\n",
"ax.grid(True, alpha=0.3)\n",
"\n",
"# Output widget to capture the plot\n",
"output = widgets.Output()\n",
"\n",
"# Capture the plot in the Output widget\n",
"with output:\n",
" plt.show()\n",
"\n",
"# Clear the current figure to prevent duplicate display\n",
"plt.close(fig)\n",
"\n",
"# Create a container to center the output\n",
"# Using HBox with layout properties to center horizontally\n",
"centered_container = widgets.HBox(\n",
" children=[output],\n",
" layout=widgets.Layout(\n",
" display='flex',\n",
" justify_content='center', # Center horizontally\n",
" align_items='center', # Center vertically\n",
" width='100%', # Full width container\n",
" min_height='400px' # Minimum height for vertical centering\n",
" )\n",
")\n",
"\n",
"# OPtions to Further Customize the Output widget's layout\n",
"output.layout = widgets.Layout(\n",
" #border='2px solid #ddd', # Add border around the plot\n",
" #padding='20px', # Add padding inside the border\n",
" #margin='10px', # Add margin outside the border\n",
" #border_radius='10px', # Rounded corners\n",
" #box_shadow='0 4px 8px rgba(0,0,0,0.1)', # Subtle shadow\n",
" #background_color='#fafafa' # Light background\n",
")\n",
"\n",
"display(centered_container)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "47b878fe-8ee0-408d-babe-314355b9fbd8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Advanced centered layout:\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "9cfe2671b5094168991f92fdde295e84",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HTML(value=\"<h2 style='text-align: center; color: #333;'>Interactive Plot Display</h2>\", layout…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Example of a more complex layout with title and controls\n",
"\n",
"def create_advanced_centered_plot():\n",
" # Create figure\n",
" fig, ax = plt.subplots(figsize=(10, 6))\n",
" \n",
" # Plot data\n",
" x = np.linspace(0, 2*np.pi, 100)\n",
" y = np.sin(x)\n",
" ax.plot(x, y, 'r-', linewidth=3)\n",
" ax.set_title('Advanced Centered Layout Example')\n",
" ax.set_xlabel('X')\n",
" ax.set_ylabel('sin(X)')\n",
" ax.grid(True)\n",
" \n",
" # Create output widget for the plot\n",
" plot_output = widgets.Output()\n",
" \n",
" with plot_output:\n",
" plt.show()\n",
" \n",
" plt.close(fig)\n",
" \n",
" # Title widget\n",
" title_widget = widgets.HTML(\n",
" value=\"<h2 style='text-align: center; color: #333;'>Interactive Plot Display</h2>\",\n",
" layout=widgets.Layout(margin='0 0 20px 0')\n",
" )\n",
" \n",
" # Create control buttons with actual functionality\n",
" refresh_btn = widgets.Button(\n",
" description='Refresh With Noise',\n",
" button_style='info',\n",
" layout=widgets.Layout(width='150px')\n",
" )\n",
" \n",
" # Function to refresh the plot with new random data\n",
" def refresh_plot(button):\n",
" # Clear the current output\n",
" plot_output.clear_output(wait=True)\n",
" \n",
" # Generate new random data\n",
" x = np.linspace(0, 2*np.pi, 100)\n",
" y = np.sin(x) + np.random.normal(0, 0.1, len(x)) # Add some noise\n",
" \n",
" # Create new figure\n",
" fig, ax = plt.subplots(figsize=(10, 6))\n",
" ax.plot(x, y, 'r-', linewidth=3)\n",
" ax.set_title(f'Refreshed Plot - {np.random.randint(1, 1000)}')\n",
" ax.set_xlabel('X')\n",
" ax.set_ylabel('sin(X) + noise')\n",
" ax.grid(True)\n",
" \n",
" # Display in the output widget\n",
" with plot_output:\n",
" plt.show()\n",
" \n",
" plt.close(fig)\n",
" \n",
" # Connect the button to the function\n",
" refresh_btn.on_click(refresh_plot)\n",
" \n",
" # Button container (centered)\n",
" button_container = widgets.HBox(\n",
" children=[refresh_btn],\n",
" layout=widgets.Layout(\n",
" display='flex',\n",
" justify_content='center',\n",
" margin='20px 0 0 0'\n",
" )\n",
" )\n",
" \n",
" # Style the plot output\n",
" plot_output.layout = widgets.Layout(\n",
" border='3px solid #2196F3',\n",
" border_radius='15px',\n",
" padding='25px',\n",
" background_color='white',\n",
" box_shadow='0 6px 12px rgba(0,0,0,0.15)'\n",
" )\n",
" \n",
" # Main container with vertical layout\n",
" main_container = widgets.VBox(\n",
" children=[title_widget, plot_output, button_container],\n",
" layout=widgets.Layout(\n",
" display='flex',\n",
" align_items='center', # Center all children horizontally\n",
" width='100%',\n",
" padding='30px',\n",
" background_color='#f5f5f5',\n",
" border_radius='10px'\n",
" )\n",
" )\n",
" \n",
" return main_container\n",
"\n",
"# Display the advanced version\n",
"print(\"Advanced centered layout:\")\n",
"advanced_layout = create_advanced_centered_plot()\n",
"display(advanced_layout)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5aa0ec94-776d-4fb8-b64e-5e3d03ace58a",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment