How to create a line chart using Matplotlib?

A line chart is one of the most common data visualization techniques used to display trends over time. Matplotlib provides the plot() function to create line charts with customizable styles and markers.

Basic Steps to Create a Line Chart

To create a line chart using matplotlib, follow these steps −

  • Import the matplotlib.pyplot module
  • Set the figure size and adjust the padding between subplots
  • Prepare your data as lists or arrays
  • Plot the data using plot() method
  • Display the figure using show() method

Example

Let's create a line chart showing population growth over different years ?

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

years = [1901, 1911, 1921, 1931, 1941, 1951,
         1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98,
              318.66, 361.09, 439.23, 548.16,
              683.33, 846.42, 1028.74]

plt.plot(years, population, color='red', marker='o')
plt.xlabel('Years')
plt.ylabel('Population (in millions)')
plt.title('Population Growth Over Time')

plt.show()
[A line chart will be displayed showing population growth from 1901 to 2011 with red markers at each data point]

Customizing Line Charts

You can customize line charts with different colors, line styles, and markers ?

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]

plt.figure(figsize=(8, 5))

# Different line styles
plt.plot(x, y1, color='blue', linestyle='-', marker='o', label='Series 1')
plt.plot(x, y2, color='green', linestyle='--', marker='s', label='Series 2')

plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Multiple Line Chart')
plt.legend()
plt.grid(True)

plt.show()
[A line chart will be displayed with two lines - one solid blue with circle markers, one dashed green with square markers, including grid and legend]

Common Parameters

Parameter Description Example Values
color Line color 'red', 'blue', '#FF5733'
linestyle Line style '-', '--', '-.', ':'
marker Data point marker 'o', 's', '^', '*'
linewidth Line thickness 1, 2, 3

Conclusion

Matplotlib's plot() function makes it easy to create line charts for visualizing trends. Use different colors, markers, and line styles to distinguish multiple data series and improve readability.

Updated on: 2026-03-26T00:05:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements