Plot Multiple lines in Matplotlib
In this tutorial, we will learn to plot multiple lines in Matplotlib using Python.
Matplotlib is a data visualizing and graph plotting library in Python which helps us to create 2D and 3D plots of data. This data can be in form of arrays, lists, and data frames.
Plotting of lines using Matplotlib involves three major steps:
- Importing libraries
- Define data values
- Plot lines over data
Lets Code
- We will import matplotlib library. Pyplot is a submodule of Matplotlib, which contains different type of plots, graphs, figures to visualize data.
# Importing library import matplotlib.pyplot as plt
- We will define data values in form of arrays.
# Define data values x = [7, 12, 22, 28, 37, 46, 49] y = [5, 12, 19, 21, 31, 27, 35] z = [2, 8 , 15, 20, 26, 32, 40]
- To plot the lines using the given data.
# Plot a simple line chart plt.plot(x, y, 'blue', label='Line 1') # Plot another line on the same chart/graph plt.plot(x, z, 'red', label='Line 2') #Plot the legends plt.legend() #Plot the lines plt.show()
plt.plot()
will take some parameters like values of X and Y coordinates, color of the line, label names which will be required to plot the lines.
plt.legend()
is responsible for plotting the labels (legends) on the top left corner of the graph. plt.show()
is used to display the output graph.
Combining all codes
# Importing library import matplotlib.pyplot as plt # Define data values x = [7, 12, 22, 28, 37, 46, 49] y = [5, 12, 19, 21, 31, 27, 35] z = [2, 8 , 15, 20, 26, 32, 40] # Plot a simple line chart plt.plot(x, y, 'blue', label='Line 1') # Plot another line on the same chart/graph plt.plot(x, z, 'red', label='Line 2') #Plot the legends plt.legend() # Plot the lines plt.show()
Output:
Leave a Reply