DEV Community

Cover image for Creating Line Plots with Object-Oriented API and Subplot Function in Python
Lohith
Lohith

Posted on

Creating Line Plots with Object-Oriented API and Subplot Function in Python

Simple Line Plot using Matplotlib

A simple line plot in Matplotlib is a basic visualization that represents the relationship between two variables (usually denoted as X and Y) using a continuous line. It's commonly used to display trends, patterns, or changes over time.

Here's how you can create a simple line plot using Matplotlib in Python:

import matplotlib.pyplot as plt
import numpy as np

# Define data values
x_values = np.array([1, 2, 3, 4])  # X-axis points
y_values = x_values * 2           # Y-axis points (twice the corresponding x-values)

# Create the line plot
plt.plot(x_values, y_values)

# Add labels and title
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Simple Line Plot")

# Display the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Figure 1

In this example:

  • We use NumPy to define the x-values (evenly spaced points from 1 to 4).
  • The y-values are calculated as twice the corresponding x-values.
  • The plt.plot() function creates the line plot.
  • We set labels for the axes and a title for the plot.

If you'd like to see more examples or explore different line plot styles, let me know! πŸš€


Object-Oriented API

Let's delve into the object-oriented API in Matplotlib.

Object-Oriented Interface (OO):

  • The object-oriented API gives you more control and customization over your plots.
  • It involves working directly with Matplotlib objects, such as Figure and Axes.
  • You create a Figure and one or more Axes explicitly, then use methods on these objects to add data, configure limits, set labels, etc.
  • This approach is more flexible and powerful, especially for complex visualizations.

Now, let's create a simple example using the object-oriented interface. We'll plot the distance traveled by an object under free-fall with respect to time.

import numpy as np
import matplotlib.pyplot as plt

# Generate data points
time = np.arange(0., 10., 0.2)
g = 9.8  # Acceleration due to gravity (m/s^2)
velocity = g * time
distance = 0.5 * g * np.power(time, 2)

# Create a Figure and Axes
fig, ax = plt.subplots(figsize=(9, 7), dpi=100)

# Plot distance vs. time
ax.plot(time, distance, 'bo-', label="Distance")
ax.set_xlabel("Time")
ax.set_ylabel("Distance")
ax.grid(True)
ax.legend()

# Show the plot
plt.show()
Enter fullscreen mode Exit fullscreen mode

Figure 2

In this example:

  • We create a Figure using plt.subplots() and obtain an Axes object (ax).
  • The ax.plot() method is used to plot the distance data.
  • We customize the plot by setting labels, grid, and adding a legend.

Feel free to explore more features of the object-oriented API for richer and more complex visualizations! πŸš€\


The Subplot() function

The plt.subplot() function in Matplotlib allows you to create multiple subplots within a single figure. You can arrange these subplots in a grid, specifying the number of rows and columns. Here's how it works:

  1. Creating Subplots:

    • The plt.subplot() function takes three integer arguments: nrows, ncols, and index.
    • nrows represents the number of rows in the grid.
    • ncols represents the number of columns in the grid.
    • index specifies the position of the subplot within the grid (starting from 1).
    • The function returns an Axes object representing the subplot.
  2. Example:
    Let's create a simple figure with two subplots side by side:

import matplotlib.pyplot as plt
import numpy as np

# Create some sample data
x = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
y2 = np.array([10, 20, 30, 40])

# Create a 1x2 grid of subplots
plt.subplot(1, 2, 1)  # First subplot
plt.plot(x, y1, label="Plot 1")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Subplot 1")
plt.grid(True)
plt.legend()

plt.subplot(1, 2, 2)  # Second subplot
plt.plot(x, y2, label="Plot 2", color="orange")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Subplot 2")
plt.grid(True)
plt.legend()

plt.tight_layout()  # Adjust spacing between subplots
plt.show()
Enter fullscreen mode Exit fullscreen mode

Figure 3

In this example:

  • We create a 1x2 grid of subplots using plt.subplot(1, 2, 1) and plt.subplot(1, 2, 2).
  • Each subplot contains a simple line plot with different data (y1 and y2).
  • We customize the labels, titles, and grid for each subplot.

Feel free to explore more complex arrangements by adjusting the nrows and ncols parameters! πŸ“ŠπŸ”

Top comments (0)