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
Selected Reading
How can I attach a pyplot function to a figure instance? (Matplotlib)
To attach a pyplot function to a figure instance, we can use figure() method and add an axes to it. This approach gives you more control over the figure and allows you to work with multiple subplots.
Steps
- Set the figure size and adjust the padding between and around the subplots.
- Create a new figure or activate an existing figure using
figure()method. - Add an
~.axes.Axesto the figure as part of a subplot arrangement. - Set a title to this axis using
set_title()method. - To display the figure, use
show()method.
Example
Here's how to create a figure instance and attach pyplot functions to it ?
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot()
ax.set_title("My Title!")
plt.show()
Working with Multiple Subplots
You can also create multiple subplots within a single figure instance ?
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
# Create first subplot
ax1 = fig.add_subplot(2, 1, 1)
x = np.linspace(0, 10, 100)
ax1.plot(x, np.sin(x))
ax1.set_title("Sine Wave")
# Create second subplot
ax2 = fig.add_subplot(2, 1, 2)
ax2.plot(x, np.cos(x))
ax2.set_title("Cosine Wave")
plt.show()
Alternative Method Using subplots()
You can also create a figure with subplots directly using subplots() ?
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
x = np.linspace(0, 10, 50)
ax1.plot(x, x**2)
ax1.set_title("Quadratic Function")
ax2.plot(x, np.sqrt(x))
ax2.set_title("Square Root Function")
plt.tight_layout()
plt.show()
Conclusion
Using figure instances gives you better control over matplotlib plots. Use fig.add_subplot() for manual subplot creation or plt.subplots() for automatic figure and axes creation.
Advertisements
