Matplotlib - fig, ax

been_29Β·2024λ…„ 7μ›” 29일
post-thumbnail

πŸ’‘ 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
      
      # Create data
      x = np.linspace(0, 10, 100)
      y = np.sin(x)
      
      # Create Figure and Axes
      fig, ax = plt.subplots()
      
      # Plot data
      ax.plot(x, y)
      
      # Set Axes labels and title
      ax.set_xlabel('X axis')
      ax.set_ylabel('Y axis')
      ax.set_title('Sine Function Plot')
      
      # Set Figure size
      fig.set_size_inches(10, 6)
      
      # Show plot
      plt.show()
    • Ex2) Multiple Subplo
      import matplotlib.pyplot as plt
      import numpy as np
      
      # Create data
      x = np.linspace(0, 10, 100)
      y1 = np.sin(x)
      y2 = np.cos(x)
      y3 = np.tan(x)
      y4 = -np.sin(x)
      
      # Create a 2x2 grid of subplots
      fig, axs = plt.subplots(2, 2)
      
      # Plot data in each subplot
      axs[0, 0].plot(x, y1)
      axs[0, 1].plot(x, y2)
      axs[1, 0].plot(x, y3)
      axs[1, 1].plot(x, y4)
      
      # Set titles for each subplot
      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')
      
      # Adjust layout
      fig.tight_layout()
      
      # Show plot
      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.
    #Example demonstrating some of these benefits:
    
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Create data
    x = np.linspace(0, 10, 100)
    y1 = np.sin(x)
    y2 = np.cos(x)
    
    # Create a figure and a 2x1 grid of subplots
    fig, axs = plt.subplots(2, 1, figsize=(8, 6))
    
    # Plot data in the first subplot
    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()
    
    # Plot data in the second subplot
    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()
    
    # Set a global title for the figure
    fig.suptitle('Trigonometric Functions')
    
    # Adjust layout for better spacing
    fig.tight_layout(rect=[0, 0, 1, 0.95])
    
    # Show plot
    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.
    #how using 'fig' and 'ax' can lead to verbose and potentially confusing code for simple tasks
    
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Simple data
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    
    # Using fig and ax for a single plot
    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()
    
    ```
profile
Data Analysis

0개의 λŒ“κΈ€