The Wayback Machine - https://web.archive.org/web/20250113203852/https://www.geeksforgeeks.org/plot-multiple-lines-in-matplotlib/
Open In App

Plot Multiple lines in Matplotlib

Last Updated : 14 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to plot multiple lines using matplotlib in Python. Let’s discuss some concepts:

  • Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
  • Line plot: Line plots can be created in Python with Matplotlib’s pyplot library. To build a line plot, first import Matplotlib. It is a standard convention to import Matplotlib’s pyplot library as plt. The plt alias will be familiar to other Python programmers.

Here we will discuss some examples to draw a line or multiple lines with different features. To do such work we must follow the steps given below:

  • Import libraries.
  • Create Data.
  • Plot the lines over data.

Plotting a single Horizontal Line

In this example, we will learn how to draw a horizontal line with the help of matplotlib. Here we will use two lists as data for two dimensions (x and y) and at last plot the line. For making a horizontal line we have to change the value of the x-axis continuously by taking the y-axis as constant.

Python
# importing package
import matplotlib.pyplot as plt

# create data
x = [10,20,30,40,50]
y = [30,30,30,30,30]

# plot line
plt.plot(x, y)
plt.show()

Output:

Plotting a single Vertical Line

In this example, we will learn how to draw a vertical line with the help of matplotlib. Here we will use two lists as data with two dimensions (x and y) and at last plot the line. For making a vertical line we have to change the value of the y-axis continuously by taking the x-axis as constant. So we change the axes to get a vertical line.

Python
# importing package
import matplotlib.pyplot as plt

# create data
x = [10,20,30,40,50]
y = [30,30,30,30,30]

# plot line
plt.plot(y,x)
plt.show()

Output:

Plotting a Horizontal and a Vertical Line 

In this example, we will learn how to draw a horizontal line and a vertical line both in one graph with the help of matplotlib. Here we will use two list as data with two dimensions (x and y) and at last plot the line with respect to the dimensions. So, in this example we merge the above both graphs to make both lines together in a graph.

Python
# importing package
import matplotlib.pyplot as plt

# create data
x = [10,20,30,40,50]
y = [30,30,30,30,30]

# plot lines
plt.plot(x, y, label = "line 1")
plt.plot(y, x, label = "line 2")
plt.legend()
plt.show()

Output:

Plotting Multiple Lines

In this example, we will learn how to draw multiple lines with the help of matplotlib. Here we will use two lists as data with two dimensions (x and y) and at last plot the lines as different dimensions and functions over the same data.

To draw multiple lines we will use different functions which are as follows:

  • y = x
  • x = y
  • y = sin(x)
  • y = cos(x)
Python
# importing package
import matplotlib.pyplot as plt
import numpy as np

# create data
x = [1,2,3,4,5]
y = [3,3,3,3,3]

# plot lines
plt.plot(x, y, label = "line 1")
plt.plot(y, x, label = "line 2")
plt.plot(x, np.sin(x), label = "curve 1")
plt.plot(x, np.cos(x), label = "curve 2")
plt.legend()
plt.show()

Output:

Plotting Multiple Lines with different Line styles

This example is similar to the above example and the enhancement is the different line styles. This can help in the modification of better visualization. 

Here we will use different line styles which are as follows:

  • –        : dashed
  • —      : double dashed
  • -.       : dashed-dotted
  • :        : dotted
Python
# importing package
import matplotlib.pyplot as plt
import numpy as np

# create data
x = [1,2,3,4,5]
y = [3,3,3,3,3]

# plot lines
plt.plot(x, y, label = "line 1", linestyle="-")
plt.plot(y, x, label = "line 2", linestyle="--")
plt.plot(x, np.sin(x), label = "curve 1", linestyle="-.")
plt.plot(x, np.cos(x), label = "curve 2", linestyle=":")
plt.legend()
plt.show()

Output:

Plot Multiple lines in Matplotlib – FAQs

How Do I Plot a Multi-Line Graph in Matplotlib?

To plot a multi-line graph in Matplotlib, you can call the plot function multiple times before showing or saving the plot. Each call to plot can specify different data sets along with their styles:

import matplotlib.pyplot as plt

# Example data
x = range(10)
y1 = [xi**2 for xi in x]
y2 = [xi**1.5 for xi in x]

# Plotting multiple lines
plt.plot(x, y1, label='x squared')
plt.plot(x, y2, label='x to the power of 1.5')
plt.legend()
plt.title('Multi-Line Graph')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

How to Plot Multiple Lines in a Single Plot?

To plot multiple lines in a single plot, simply use the plot function multiple times with different data sets, as shown above. You can customize the appearance of each line with additional arguments, such as color, linewidth, and linestyle.

How Do I Make Multiple Plots in Matplotlib Python?

For multiple separate plots (subplots) in a single figure, you can use plt.subplot() to specify the grid dimensions and the position of each plot:

import matplotlib.pyplot as plt

# Data for plotting
x = range(10)
y1 = [xi**2 for xi in x]
y2 = [xi**3 for xi in x]

# First subplot
plt.subplot(1, 2, 1) # 1 row, 2 columns, first subplot
plt.plot(x, y1, 'r-') # red line
plt.title('Square')

# Second subplot
plt.subplot(1, 2, 2) # 1 row, 2 columns, second subplot
plt.plot(x, y2, 'g-') # green line
plt.title('Cube')

# Show the figure
plt.show()

How to Plot Multiple Columns in Matplotlib?

If you have a dataset with multiple columns (e.g., a DataFrame), you can plot each column as a line on the same graph:

import pandas as pd
import matplotlib.pyplot as plt

# Creating a DataFrame
data = {'x': range(10), 'y1': [xi**2 for xi in range(10)], 'y2': [xi**3 for xi in range(10)]}
df = pd.DataFrame(data)

# Plotting multiple columns
plt.plot(df['x'], df['y1'], label='y1 = x^2')
plt.plot(df['x'], df['y2'], label='y2 = x^3')
plt.legend()
plt.title('Multiple Columns Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

How Do I Plot a Continuous Graph in Matplotlib?

In Matplotlib, you can make a graph appear continuous by ensuring you have enough data points and by using line styles that promote continuity. For functions, it helps to sample the data at a higher resolution:

import numpy as np
import matplotlib.pyplot as plt

# High-resolution data for smoothness
x = np.linspace(0, 10, 500)
y = np.sin(x)

# Plotting
plt.plot(x, y, '-r', label='sin(x)')
plt.legend()
plt.title('Continuous Graph of sin(x)')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
plt.show()

This plot of sin(x) will appear smooth and continuous due to the high density of points and the use of a solid line style


Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg