WikiGalaxy

Personalize

Understanding Matplotlib Figure and Axes

Introduction to Matplotlib

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is widely used in data analysis, scientific computing, and machine learning to visualize data patterns.

Figure and Axes

In Matplotlib, a Figure is the entire window where the plot is displayed, while Axes are the individual plots within the figure. A single figure can contain multiple axes, which allows for complex visualizations.

Creating a Simple Plot

Let's start by creating a simple line plot using Matplotlib's figure and axes.


import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])

plt.show()
        

Explanation

In this example, we create a figure and a set of subplots using plt.subplots(). The ax.plot() function is used to plot a line graph.

Adding Titles and Labels

Enhance your plot with titles and labels to make it more informative.


import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])
ax.set_title('Simple Line Plot')
ax.set_xlabel('X-axis Label')
ax.set_ylabel('Y-axis Label')

plt.show()
        

Explanation

Here, the set_title(), set_xlabel(), and set_ylabel() methods are used to add a title and labels to the x and y axes respectively.

Creating Multiple Subplots

You can create multiple subplots within a single figure to compare different data sets.


import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot([1, 2, 3], [1, 4, 9])
axs[0, 1].plot([1, 2, 3], [1, 2, 3])
axs[1, 0].plot([1, 2, 3], [3, 2, 1])
axs[1, 1].plot([1, 2, 3], [9, 4, 1])

plt.show()
        

Explanation

This example demonstrates how to create a 2x2 grid of subplots using plt.subplots(2, 2). Each subplot can be accessed and customized individually.

Customizing Plot Appearance

Matplotlib allows you to customize the appearance of your plots, including colors, line styles, and markers.


import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30], color='red', linestyle='--', marker='o')

plt.show()
        

Explanation

In this plot, the line color is set to red, the line style is dashed, and circle markers are added at each data point using the color, linestyle, and marker parameters.

Saving Figures

Once you have created a plot, you may want to save it as an image file for later use or sharing.


import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.savefig('my_plot.png')

plt.show()
        

Explanation

The plt.savefig() function saves the current figure to a file. In this example, the plot is saved as "my_plot.png".

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025