6.3. Matplotlib interfaces#
It provides both a MATLAB-style interface and an object-oriented interface for generating plots. Let’s briefly explore each of these interfaces:
6.3.1. MATLAB-style Interface#
The MATLAB-style interface in matplotlib
is inspired by the way plotting is done in MATLAB. It is convenient for users familiar with MATLAB’s plotting syntax. In this style, you can create plots directly without explicitly creating Figure and Axes objects [Pajankar, 2021, Matplotlib Developers, 2024].
An example of the MATLAB-style interface in matplotlib
:
import matplotlib.pyplot as plt
# Use a custom style
plt.style.use('../mystyle.mplstyle')
# Data
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
# Simple plot using MATLAB-style interface
plt.figure(figsize=(6, 4)) # Set the figure size
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Plot', weight = 'bold')
plt.grid(True)
In this style, the plt
module is used to create and customize the plot, and the various plot settings are directly applied to the active plot.
6.3.2. Object-oriented Interface#
The object-oriented (OO) interface in matplotlib
is more explicit and provides fine-grained control over the plot elements. It involves explicitly creating Figure and Axes objects, allowing you to work with them separately (Vanderplas, 2016).
Here’s an example of the object-oriented interface in matplotlib
:
# Data
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
# Create Figure and Axes objects
fig, ax = plt.subplots(figsize=(6, 4))
# Plot using object-oriented interface
ax.plot(x, y)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Simple Plot', weight = 'bold')
ax.grid(True)
In this style, you explicitly create a Figure using plt.subplots()
and then work with the Axes object (referred to as ax
in this example) to plot and customize the elements.
6.3.3. Similarities and differences#
Some of the similarities and differences between the MATLAB-style interface and the object-oriented interface in Matplotlib [Pajankar, 2021, Matplotlib Developers, 2024]:
Similarities:
Creating Visualizations: Both interfaces allow you to create a wide variety of visualizations, catering to different data representation needs.
Plot Customization: Whether using the MATLAB-style or object-oriented interface, you can customize aspects such as titles, labels, colors, markers, and axes properties.
Data Visualization: Both interfaces are designed to visually represent data patterns, trends, and relationships, enhancing data understanding.
Access to Matplotlib Functions: Regardless of the chosen interface, you have access to the same underlying Matplotlib functions and capabilities. This consistency ensures you can achieve similar results using either approach.
Widespread Usage: Both interfaces are widely used within the Matplotlib community, and resources such as tutorials and examples are available for both approaches.
Differences:
Syntax and Approach:
MATLAB-style Interface: This interface employs a syntax reminiscent of MATLAB. It’s concise and suitable for quick plotting without the need to explicitly manage Figure and Axes objects.
Object-Oriented Interface: This approach involves creating explicit Figure and Axes objects. It provides greater control and flexibility over plot components, making it suitable for complex plots and advanced customization.
Figure and Axes Management:
MATLAB-style Interface: The interface automatically manages the creation of figures and axes behind the scenes, which is advantageous for quick plotting.
Object-Oriented Interface: In this approach, you explicitly create and manipulate Figure and Axes objects, offering more control over subplot arrangements and component placements.
Complex Customization:
MATLAB-style Interface: While you can customize plots, the level of customization is somewhat limited compared to the object-oriented approach.
Object-Oriented Interface: This approach allows for more intricate customization, making it ideal for creating complex layouts, multiple subplots, and specialized visuals.
Transition from MATLAB:
MATLAB-style Interface: If you’re familiar with MATLAB’s plotting, transitioning to the MATLAB-style interface might be smoother.
Object-Oriented Interface: It’s a departure from MATLAB’s syntax, but it offers advantages in terms of flexibility and control.
Use Cases:
MATLAB-style Interface: Well-suited for quick exploratory data analysis and simple visualizations.
Object-Oriented Interface: Preferable for advanced customization, complex layouts, and precise control over plot components.
Summary
The choice between the two interfaces depends on factors like familiarity with MATLAB, the complexity of your visualizations, and your preference for either quick plotting or advanced customization. It’s also worth noting that you can mix and match both approaches within a single project, depending on the specific requirements of each plot.
Both the MATLAB-style and object-oriented interfaces are valid ways to work with matplotlib
. The choice between the two often comes down to personal preference and the complexity of the plot you’re creating. The object-oriented interface is particularly useful when you want to create multiple subplots or customize the plot elements in a more detailed manner.
6.3.4. Adjusting the Plot#
In matplotlib
, you can use the set
method to adjust axis limits, labels, and more when using the object-oriented interface. The set
method allows you to modify various properties of the Axes
object. Here’s how you can use set
to customize the plot:
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
# Create Figure and Axes objects
fig, ax = plt.subplots(figsize=(6, 4))
# Plot using object-oriented interface
line, = ax.plot(x, y)
# Customize axis limits
ax.set_xlim(0, 5)
ax.set_ylim(0, 30)
# Customize axis labels
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
# Customize title
ax.set_title('Customized Plot')
# Customize grid
ax.grid(True)
# Customize legend
line.set_label('My Data')
_ = ax.legend()
In the example above, the set_xlim
and set_ylim
methods are used to adjust the axis limits, set_xlabel
and set_ylabel
are used to set the axis labels, and set_title
is used to customize the title of the plot. The grid
method is used to enable the grid lines, and the legend
method is used to add a legend to the plot.
Note that when using the object-oriented interface, the plot
method returns a Line2D object representing the plot. By storing this returned value in a variable (in this case, line
), you can use it later to customize properties of the line, such as adding a label for the legend using set_label
.
You can combine all the settings in one set
method call to customize various properties of the plot and axes simultaneously. This can be particularly useful when you want to apply multiple settings at once. Here’s how you can achieve this:
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
# Create Figure and Axes objects
fig, ax = plt.subplots(figsize=(6, 4))
# Plot using object-oriented interface
line, = ax.plot(x, y, label = 'My Data')
# Combine settings in one set method call
ax.set(
xlim=(0, 5),
ylim=(0, 30),
xlabel='X-axis',
ylabel='Y-axis',
title='Customized Plot',
)
# Customize grid
ax.grid(True)
# legend
_ = ax.legend()
In this example, the set
method is used to combine multiple settings within a single call. The settings are provided as keyword arguments, where each argument corresponds to a specific property that you want to customize. The properties are specified using their respective names (e.g., xlim
, ylim
, xlabel
, ylabel
, and title
).
You can add as many settings as you need to this set
method call, making it a convenient way to customize multiple properties in one go.
Remember that this method works with the object-oriented interface of matplotlib
. If you are using the MATLAB-style interface (plt
module), you will need to use separate method calls for each setting as shown in the previous examples.
Adjusting the plot in Matplotlib involves customizing various aspects of the visualization to enhance its appearance, readability, and impact. Here are some common adjustments you can make to your Matplotlib plots [Pajankar, 2021, Matplotlib Developers, 2024]:
Changing Figure Size: You can control the size of the entire figure using the
plt.figure(figsize=(width, height))
function. This is particularly useful when you need to ensure your plot fits well within your document or presentation.Adding Titles and Labels: Titles and labels provide context to your plot. Use
plt.title()
,plt.xlabel()
, andplt.ylabel()
to add a title and label the axes, respectively.Setting Axis Limits: Adjust the visible range of your data on the x and y axes using
plt.xlim()
andplt.ylim()
.Adding Gridlines: Gridlines can aid in understanding data relationships. Enable them using
plt.grid(True)
.Changing Line Styles and Markers: You can customize the appearance of lines and markers using options like
linestyle
andmarker
when using functions likeplt.plot()
.Changing Colors: Customize colors using options like
color
or specifying color codes. You can use named colors (‘blue’, ‘red’, etc.) or hexadecimal color codes.Adding Legends: If you have multiple datasets, add a legend to differentiate them. Use
plt.legend()
and provide labels for each dataset.Adjusting Tick Labels: Customize tick labels on axes using functions like
plt.xticks()
andplt.yticks()
. You can provide custom tick positions and labels.Adding Annotations and Text: You can annotate points on the plot or add text explanations using functions like
plt.annotate()
andplt.text()
.Changing Background and Grid Style: Change the appearance of the plot background and gridlines using styles like ‘dark_background’ or ‘whitegrid’. Use
plt.style.use()
to apply the desired style.Creating Subplots: Use
plt.subplots()
to create multiple plots in a grid. This is useful when you want to visualize multiple datasets side by side.Saving Plots: Save your plot to a file using
plt.savefig('filename.png')
. You can save in various formats such as PNG, PDF, SVG, etc.
An example illustrating some of these adjustments:
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a Figure and Axes object
fig, ax = plt.subplots(figsize=(5, 5))
# Plot the data using the Axes object
ax.plot(x, y, marker='o', color='RoyalBlue', linestyle='--', label='Data')
# Set multiple properties using the Axes object
ax.set(
xlabel='X-axis',
ylabel='Y-axis',
title='Adjusted Plot Example',
aspect='equal', # Equal scaling for both axes
adjustable='datalim', # Adjust aspect based on data limits
)
# Add gridlines using the Axes object
ax.grid(True)
# Add legend using the Axes object
ax.legend()
# tight layout
plt.tight_layout()
# Saving the plot
fig.savefig('adjusted_plot.png') # Save the plot
Table 6.2 summarizes the changes for transitioning between MATLAB-style functions and object-oriented methods in matplotlib.
MATLAB-Style |
Object-Oriented |
---|---|
plt.xlabel() |
ax.set_xlabel() |
plt.ylabel() |
ax.set_ylabel() |
plt.xlim() |
ax.set_xlim() |
plt.ylim() |
ax.set_ylim() |
plt.title() |
ax.set_title() |
plt.plot() |
ax.plot() |
plt.scatter() |
ax.scatter() |
plt.bar() |
ax.bar() |
plt.hist() |
ax.hist() |
plt.imshow() |
ax.imshow() |
plt.legend() |
ax.legend() |
plt.grid() |
ax.grid() |
plt.xticks() |
ax.set_xticks() |
plt.yticks() |
ax.set_yticks() |
plt.figure() |
fig, ax = plt.subplots() |
plt.subplots() |
N/A (use fig, ax = plt.subplots() instead) |
plt.show() |
plt.show() (unchanged) |
Note
Please note that this is not an exhaustive list, but it covers some commonly used functions. When transitioning from MATLAB-style to object-oriented methods, you’ll generally need to replace plt
with ax.
for most of the function calls related to customizing the plot elements. Additionally, for creating figures and subplots, you’ll use plt.subplots()
to get the fig
and ax
objects to work with.
You can also use ax.set
to combine multiple settings in one call. For example:
ax.set(xlabel='Categories', ylabel='Values', title='Bar Plot Example')