π‘ How to use fig, ax in Matplotlib
- Concepts
- Figure (βfigβ) : Represent the entire drawing or canvas. It can contain multiple plots.
- Axes (βaxβ) : Represent a single plot or graph within the figure. A figure can contain multiple axes.
- Form
fig, ax = plt.subplots()
- Usability
- Figure : Used to set the overall size, resolution, and layout of the entire plot
- Axes : Used to set the data, labels, titles, and ranges of individual plots.
- Examples
- Ex1) Single Plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_title('Sine Function Plot')
fig.set_size_inches(10, 6)
plt.show()
- Ex2) Multiple Subplo
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = -np.sin(x)
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y1)
axs[0, 1].plot(x, y2)
axs[1, 0].plot(x, y3)
axs[1, 1].plot(x, y4)
axs[0, 0].set_title('Sine')
axs[0, 1].set_title('Cosine')
axs[1, 0].set_title('Tangent')
axs[1, 1].set_title('Negative Sine')
fig.tight_layout()
plt.show()
π Benefits of Using βfigβ and βaxβ in Matplotlib
- Clear Structure and Organization
- Separation of Concerns : βfigβ represents the entire figure, while βaxβ represents individual plots. This clear separation allows for better organization and management of the plotting code.
- Hierarchical Design : By distinguishing between the figure and its axes, it is easier to apply different settings and modifications at different levels.
- Flexibility in Layout Management
- Multiple Subplots : βplt.subplots()β allows you to create multiple subplots within a single figure, making it easy to compare different datasets or different views of the same data.
- Custom Layouts : Using βGridSpecβ, you can create complex layouts with varying subplot sizes and positions, giving you control over the presentation of your data.
- Enhanced Customization
- Individual Plot Control : Each βaxβ object can be customized independently, allowing you to set labels, titles, ticks, limits, and styles for each subplot without affecting others.
- Global Settings : The βfigβ object can be used to set properties that affect the entire figure, such as size, DPI, and overall layout, ensuring consistency across all subplots.
- Improved Code Readability and Maintenance
- Modular Code : By separating figure-level and axes-level customizations, the code becomes more modular and easier to understand, debug, and maintain.
- Reusable Components : You can define common customizations for βfigβ and βaxβ and reuse them across different plots, reducing code duplication and enhancing consistency.
- Advanced Plotting Capabilities
- Annotations and Insets : You can add annotations, and other custom elements to specific axes, providing more informative and detailed visualizations.
- Interactive Features : The βaxβ object supports interactive features like zooming and panning, making it easier to explore the data within individual subplots.
- Integration with Other Libraries
- Seamless Integration : βfigβ and βaxβ are compatible with other plotting libraries and tools in the Python ecosystem, such as Seaborn and Pandas plotting, allowing for enhanced functionality and customization.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axs = plt.subplots(2, 1, figsize=(8, 6))
axs[0].plot(x, y1, label='Sine')
axs[0].set_title('Sine Function')
axs[0].set_xlabel('X axis')
axs[0].set_ylabel('Y axis')
axs[0].legend()
axs[1].plot(x, y2, label='Cosine', color='r')
axs[1].set_title('Cosine Function')
axs[1].set_xlabel('X axis')
axs[1].set_ylabel('Y axis')
axs[1].legend()
fig.suptitle('Trigonometric Functions')
fig.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()
π Drawbacks to consider
- Complexity for Simple Plots
- Overhead : For simple, single plots, using βfigβ and βaxβ can add unnecessary complexity. The additional lines of code to create and manage these objects might be overkill when a straightforward βplt.plot()β could suffice.
- Steeper Learning Curve
- Understanding the Hierarchy : New users might find the concept of figures and axes confusing initially. Understanding how these objects interact and how to manipulate them requires a bit more effort compared to basic plotting functions.
- More Code to Write : Managing βfigβ and βaxβ objects often requires writing more code, which can be intimidating for beginners who just want to create quick plots.
- Verbosity
- Increased Code Length : Using βfigβ and βaxβ can lead to more verbose code. This can be seen as a drawback when the goal is to create quick visualizations without much customization.
- Repetitive Code : If not managed properly, customization of individual βaxβ objects can lead to repetitive code, especially when dealing with multiple subplots that share similar settings.
- Potential for Mismanagement
- Coordination Between βfigβ and βaxβ : Improper coordination between figure and axes can lead to issues like overlapping plots or improper layout management, which can make debugging more difficult.
- Statefulness : Matplotlib's state-based interface (using βpltβ) can sometimes interfere with the object-oriented approach (βfigβ and βaxβ), leading to unexpected behaviors if both styles are mixed without careful management.
- Performance
- Resource Intensive : For very large figures with many subplots, managing multiple axes can become resource-intensive, potentially impacting performance. This is especially true if each subplot involves complex rendering or large datasets.
- Memory Usage : Creating and holding onto many figure and axes objects can increase memory usage, which might be a concern in memory-constrained environments.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Sine Function')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
```