Matplotlib Plot a Line

As a developer working on a data visualization project, I needed to create clear and informative line plots to present some trend analysis. As I’ve discovered over my years working with Python, Matplotlib is incredibly useful, yet sometimes the basics can trip us up.

In this article, I’ll walk through several approaches to plot lines in Matplotlib, from the simplest implementations to more customized solutions.

So let’s get started..

Basic Line Plot with Matplotlib

The simplest way to create a line plot in Matplotlib is by using the plot() function. Here’s how you can do it:

import matplotlib.pyplot as plt
import numpy as np

# Create some sample data
x = np.arange(0, 10, 0.1)
y = np.sin(x)

# Create the plot
plt.plot(x, y)
plt.title('Basic Sine Wave Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.grid(True)
plt.show()

I executed the above example code and added the screenshot below.

matplotlib line plot

This creates a simple sine wave. The plot() function automatically connects the data points with straight lines.

Read What is Matplotlib Inline in Python

Customize Line Style, Color, and Width

You can easily customize how your line looks by adjusting parameters:

import matplotlib.pyplot as plt
import numpy as np

# Create some sample data
x = np.arange(0, 10, 0.1)
y = np.sin(x)

# Create a customized line plot
plt.plot(x, y, linestyle='--', color='red', linewidth=2, label='Sine Wave')
plt.title('Customized Sine Wave')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.legend()
plt.grid(True)
plt.show()

I executed the above example code and added the screenshot below.

matplotlib plot line

In this example, I’ve used a dashed red line that’s thicker than the default. You can use various line styles like - (solid), -- (dashed), -. (dash-dot), or : (dotted).

Plot Multiple Lines

Often, you’ll want to compare multiple datasets by plotting several lines on the same graph:

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

# Plot multiple lines
plt.plot(x, y1, color='blue', label='Sine')
plt.plot(x, y2, color='red', label='Cosine')

plt.title('Sine and Cosine Waves')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.legend()
plt.grid(True)
plt.show()

I executed the above example code and added the screenshot below.

line plot matplotlib

This plots both sine and cosine waves on the same axes, with different colors and labels in the legend.

Use Object-Oriented Interface

While the examples above use Matplotlib’s pyplot interface, the object-oriented approach gives you more control:

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.arange(0, 10, 0.1)
y = np.sin(x)

# Create figure and axis objects
fig, ax = plt.subplots(figsize=(10, 6))

# Plot on the axis
line, = ax.plot(x, y, color='green', linewidth=2)

# Customize the plot
ax.set_title('Object-Oriented Line Plot')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.grid(True)

plt.show()

This approach is especially useful for complex plots or when you need to modify plot elements after creation.

Check out Matplotlib Dashed Line

Add Markers to Line Plots

Sometimes you want to highlight the actual data points on your line:

import matplotlib.pyplot as plt
import numpy as np

# Create sample data - fewer points to make markers visible
x = np.arange(0, 10, 0.5)
y = np.sin(x)

# Plot with markers
plt.plot(x, y, 'bo-', markersize=8, linewidth=1.5, label='Sine with markers')
# 'bo-' means blue color, circle markers, with a line

plt.title('Line Plot with Markers')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.legend()
plt.grid(True)
plt.show()

In this example, I’ve added blue circle markers at each data point. The 'bo-' is a shorthand format where ‘b’ stands for blue, ‘o’ for circle markers, and ‘-‘ for a solid line.

Real-World Example: Plotting Stock Prices

Let’s create a more practical example. Here’s how to plot stock price data:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import datetime, timedelta

# Generate sample stock data
np.random.seed(42)
dates = [datetime(2023, 1, 1) + timedelta(days=i) for i in range(365)]
stock_prices = [100]

for i in range(1, 365):
    # Random walk with slight upward bias
    change = np.random.normal(0.05, 1)
    stock_prices.append(max(stock_prices[-1] + change, 50))

# Convert to DataFrame for easier handling
df = pd.DataFrame({'Date': dates, 'Price': stock_prices})

# Create the plot
plt.figure(figsize=(12, 6))
plt.plot(df['Date'], df['Price'], color='#0066cc', linewidth=2)

plt.title('ACME Corporation Stock Price (2023)', fontsize=15)
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.grid(True, linestyle='--', alpha=0.7)

# Format the x-axis to show months
plt.gcf().autofmt_xdate()

# Add some annotations
max_price_idx = df['Price'].idxmax()
plt.scatter(df.loc[max_price_idx, 'Date'], df.loc[max_price_idx, 'Price'], 
            color='green', s=100, zorder=5)
plt.annotate(f'Peak: ${df["Price"].max():.2f}', 
             (df.loc[max_price_idx, 'Date'], df.loc[max_price_idx, 'Price']),
             xytext=(15, 15), textcoords='offset points',
             arrowprops=dict(arrowstyle='->', color='black'))

plt.tight_layout()
plt.show()

This creates a realistic stock price chart with annotations highlighting the peak price.

Read Draw a Vertical Line Matplotlib

Create Line Plots with Subplots

If you need to compare multiple datasets side by side:

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(-x/5) * np.sin(x)

# Create a figure with 4 subplots
fig, axs = plt.subplots(2, 2, figsize=(12, 8))
fig.suptitle('Multiple Trigonometric Functions', fontsize=16)

# Plot in each subplot
axs[0, 0].plot(x, y1, color='blue')
axs[0, 0].set_title('Sine Function')
axs[0, 0].grid(True)

axs[0, 1].plot(x, y2, color='red')
axs[0, 1].set_title('Cosine Function')
axs[0, 1].grid(True)

axs[1, 0].plot(x, y3, color='green')
axs[1, 0].set_title('Tangent Function')
axs[1, 0].set_ylim(-5, 5)  # Limit y-axis for better visibility
axs[1, 0].grid(True)

axs[1, 1].plot(x, y4, color='purple')
axs[1, 1].set_title('Damped Sine Wave')
axs[1, 1].grid(True)

plt.tight_layout()
plt.subplots_adjust(top=0.9)  # Adjust for the figure title
plt.show()

This creates a 2×2 grid of subplots, each showing a different mathematical function.

Read Horizontal Line Matplotlib

Add Shaded Regions to Line Plots

You can enhance your line plots by adding shaded regions to highlight areas of interest:

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create the plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2, label='Sine Wave')

# Add shaded region between y=0 and the sine wave where sine is positive
positive_mask = y > 0
plt.fill_between(x, y, 0, where=positive_mask, color='blue', alpha=0.3, label='Positive Region')

# Add shaded region between y=0 and the sine wave where sine is negative
negative_mask = y < 0
plt.fill_between(x, y, 0, where=negative_mask, color='red', alpha=0.3, label='Negative Region')

plt.title('Sine Wave with Shaded Regions')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.legend()
plt.grid(True)
plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)  # Add a line at y=0

plt.show()

This example shades the areas above and below the x-axis with different colors, making it easy to distinguish positive and negative values.

I’ve found that creating effective line plots is a fundamental skill for data visualization. The examples above cover most of what you’ll need for day-to-day work, but Matplotlib offers even more customization options if you need them.

When designing your plots, remember to keep your audience in mind, choose colors, styles, and annotations that help convey your message clearly. And don’t forget that sometimes simpler is better!

Other Python articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.