How to modify existing figure instance in Matplotlib?

In this article, we will learn how to modify an existing figure instance in Matplotlib. A figure instance represents the entire visualization window that can contain plots, titles, labels, and legends.

Matplotlib is a popular Python library for creating visualizations. It provides both a simple interface through pyplot and an object-oriented approach for fine-grained control over figure properties.

Creating and Accessing Figure Instances

To work with figures, we first need to create or access an existing figure instance. Here are the common approaches ?

import matplotlib.pyplot as plt
import numpy as np

# Method 1: Create a new figure
fig = plt.figure(figsize=(8, 6))

# Method 2: Get current figure
fig = plt.gcf()  # Get Current Figure

print(f"Figure size: {fig.get_size_inches()}")
Figure size: [8. 6.]

Basic Figure Modifications

Changing Figure Size

You can modify the figure size using set_size_inches() method ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Create figure and plot
fig = plt.figure()
plt.plot(x, y, 'bo-', label='Sample Data')

# Modify figure size
fig.set_size_inches(10, 6)

plt.title('Modified Figure Size')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Adding Multiple Elements

You can add titles, labels, and other elements to customize the figure ?

import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create figure
fig = plt.figure(figsize=(10, 6))

# Plot data
plt.plot(x, y1, 'r-', label='sin(x)', linewidth=2)
plt.plot(x, y2, 'b--', label='cos(x)', linewidth=2)

# Modify figure properties
plt.title('Trigonometric Functions', fontsize=16, fontweight='bold')
plt.xlabel('Angle (radians)', fontsize=12)
plt.ylabel('Value', fontsize=12)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)

# Set axis limits
plt.xlim(0, 2*np.pi)
plt.ylim(-1.2, 1.2)

plt.show()

Object-Oriented Approach

The object-oriented interface provides better control over figure modifications ?

import matplotlib.pyplot as plt
import numpy as np

# Create figure and axes
fig, ax = plt.subplots(figsize=(8, 6))

# Generate sample data
np.random.seed(42)
data = np.random.normal(0, 1, 1000)

# Create histogram
ax.hist(data, bins=30, color='skyblue', alpha=0.7, edgecolor='black')

# Modify axes properties
ax.set_title('Normal Distribution Histogram', fontsize=14)
ax.set_xlabel('Value', fontsize=12)
ax.set_ylabel('Frequency', fontsize=12)

# Modify figure properties
fig.suptitle('Statistical Analysis', fontsize=16, y=0.98)

# Add text annotation
ax.text(0.02, 0.95, f'n = {len(data)}', transform=ax.transAxes, 
        verticalalignment='top', bbox=dict(boxstyle='round', facecolor='white'))

plt.tight_layout()
plt.show()

Modifying Existing Plots

You can retrieve and modify existing figures after they've been created ?

import matplotlib.pyplot as plt
import numpy as np

# Create initial plot
x = np.linspace(0, 5, 50)
y = x**2

plt.plot(x, y, 'g-')
plt.title('Initial Plot')

# Get current figure and modify it
fig = plt.gcf()
ax = plt.gca()  # Get Current Axes

# Add more data to existing plot
y2 = x**3 / 5
ax.plot(x, y2, 'r--', linewidth=2)

# Modify existing elements
ax.set_title('Modified Plot with Additional Data')
ax.set_xlabel('X values')
ax.set_ylabel('Y values')
ax.legend(['x²', 'x³/5'])
ax.grid(True, alpha=0.3)

# Change figure background
fig.patch.set_facecolor('lightgray')

plt.show()

Common Modification Methods

Method Purpose Example
set_size_inches() Change figure size fig.set_size_inches(10, 8)
suptitle() Add figure title fig.suptitle('Main Title')
tight_layout() Adjust spacing fig.tight_layout()
savefig() Save figure fig.savefig('plot.png')

Saving Modified Figures

After modifying a figure, you can save it to various formats ?

import matplotlib.pyplot as plt
import numpy as np

# Create and customize a figure
fig, ax = plt.subplots(figsize=(8, 6))

x = np.linspace(0, 10, 100)
y = np.exp(-x/3) * np.sin(x)

ax.plot(x, y, 'purple', linewidth=2)
ax.set_title('Damped Oscillation', fontsize=14)
ax.set_xlabel('Time')
ax.set_ylabel('Amplitude')
ax.grid(True, alpha=0.3)

# Save with different formats (commented to avoid file creation)
# fig.savefig('damped_oscillation.png', dpi=300, bbox_inches='tight')
# fig.savefig('damped_oscillation.pdf', bbox_inches='tight')

plt.show()

Conclusion

Modifying existing figure instances in Matplotlib is straightforward using methods like set_size_inches(), suptitle(), and accessing figures with plt.gcf(). The object-oriented approach provides more control and is recommended for complex modifications.

Updated on: 2026-03-27T10:28:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements