Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I show the same Matplotlib figure several times in a single IPython notebook?
To show the same Matplotlib figure several times in a single Jupyter notebook, you can use the fig.show() method or plt.show(). This is useful when you want to display the same plot multiple times at different points in your notebook.
Basic Approach Using fig.show()
Create a figure once and display it multiple times using the figure's show method ?
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create figure and plot data
fig, ax = plt.subplots()
ax.plot([2, 4, 7, 5, 4, 1])
ax.set_title('Sample Line Plot')
# Show the figure first time
fig.show()
Now you can show the same figure again later in your notebook ?
# Display the same figure again fig.show()
Using plt.show() Method
Alternatively, you can use plt.show() to display the current figure ?
import matplotlib.pyplot as plt
# Create a simple plot
plt.figure(figsize=(7, 3))
plt.plot([1, 3, 6, 4, 3, 2])
plt.title('Another Sample Plot')
# Show the plot first time
plt.show()
# Show the same plot again
plt.show()
Storing Figure for Later Display
You can store the figure object and display it at any point in your notebook ?
import matplotlib.pyplot as plt
def create_sample_plot():
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(['A', 'B', 'C', 'D'], [3, 7, 2, 5])
ax.set_title('Sample Bar Chart')
return fig
# Create and store the figure
my_figure = create_sample_plot()
# Display it multiple times
my_figure.show()
print("Displaying the same figure again...")
my_figure.show()
Key Points
-
fig.show()displays a specific figure object -
plt.show()displays the current active figure - The figure object remains in memory and can be displayed multiple times
- Use
%matplotlib inlineor%matplotlib automagic commands in Jupyter for proper display
Conclusion
Use fig.show() to display the same Matplotlib figure multiple times in a Jupyter notebook. Store the figure object in a variable to reference and display it at different points in your workflow.
