Python Plot Multiple Lines Using Matplotlib - Python Guides (2023)

In thisPython tutorial, we will discuss, How toplot multiple lines using matplotlibin Python, and we shall also cover the following topics:

  • Python plot multiple lines on same graph
  • Python plot multiple lines of different color
  • Python plot multiple lines with legend
  • Python plot multiple lines from array
  • Python plot multiple lines from dataframe
  • Python plot multiple lines for loop
  • Python plot multiple lines with different y axis
  • Python plot multiple lines time series
  • Python plot multiple lines in 3D
  • Matplotlib plot multiple lines with same color.
  • Matplotlib plot title multiple lines
  • Matplotlib plot multiple lines in subplot
  • Matplotlib plot multiple lines different length
  • Matplotlib plot multiple lines seaborn
  • Matplotlib plot multiple lines from csv files

Table of Contents

Python plot multiple lines on same graph

Python provides the Matplotlib library, the most commonly used package for data visualization. It provides a wide variety of plots, tools, and extended libraries for effective data visualization. You can create 2D and 3D plots of the data from different sources like lists, arrays, Dataframe, and external files (CSV, JSON, etc.).

It provides an API (or simply a submodule) called pyplot that contains different types of plots, figures, and related functions to visualize data. A line chart is a type of chart/graph that shows the relationship between two quantities on an X-Y plane.

You can also plot more than one line on the same chart/graph using matplotlib in python. You can do so, by following the given steps:

  • Import necessary libraries (pyplot from matplotlib for visualization, numpy for data creation and manipulation, pandas for Dataframe and importing the dataset, etc).
  • Defining the data values that has to be visualized (Define x and y or array or dataframe).
  • Plot the data (multiple lines) and adding the features you want in the plot (title, color pallete, thickness, labels, annotation, etc…).
  • Show the plot (graph/chart). You can also save the plot.

Let’s plot a simple graph containing two lines in python. So, open up your IPython shell or Jupiter notebook, and follow the code below:

# Importing packagesimport matplotlib.pyplot as plt# Define data valuesx = [7, 14, 21, 28, 35, 42, 49]y = [5, 12, 19, 21, 31, 27, 35]z = [3, 5, 11, 20, 15, 29, 31]# Plot a simple line chartplt.plot(x, y)# Plot another line on the same chart/graphplt.plot(x, z)plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (1)

In the above example, the data is prepared as lists as x, y, z. Then matplot.pyplot.plot() function is called twice with different x, y parameters to plot two different lines. At the end, matplot.pyplot.show() function is called to display the graph containing the properties defined before the function.

Read: How to install matplotlib

Python plot multiple lines of different color

You can specify the color of the lines in the chart in python using matplotlib. You have to specify the value for the parameter color in the plot() function of matplotlib.pyplot.

There are various colors available in python. You can either specify the color by their name or code or hex code enclosed in quotes.

You can specify the color parameter as a positional argument (eg., ‘c’ –> means cyan color; ‘y’ –> means yellow color) or as keyword argument (eg., color=’r’ –> means red color; color=’green’; color=’#B026FF’ –> means neon purple color).

# Importing packagesimport matplotlib.pyplot as plt# Define data valuesx = [7, 14, 21, 28, 35, 42, 49]y = [5, 12, 19, 21, 31, 27, 35]z = [3, 5, 11, 20, 15, 29, 31]# Plot a simple line chartplt.plot(x, y, 'c')# Plot another line on the same chart/graphplt.plot(x, z, 'y')plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (2)

Read: Matplotlib plot a line

Python plot multiple lines with legend

You can add a legend to the graph for differentiating multiple lines in the graph in python using matplotlib by adding the parameter label in the matplotlib.pyplot.plot() function specifying the name given to the line for its identity.

After plotting all the lines, before displaying the graph, call matplotlib.pyplot.legend() method, which will add the legend to the graph.

# Importing packagesimport matplotlib.pyplot as plt# Define data valuesx = [7, 14, 21, 28, 35, 42, 49]y = [5, 12, 19, 21, 31, 27, 35]z = [3, 5, 11, 20, 15, 29, 31]# Plot a simple line chartplt.plot(x, y, 'g', label='Line y')# Plot another line on the same chart/graphplt.plot(x, z, 'r', label='Line z')plt.legend()plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (3)

Python plot multiple lines from array

You can plot multiple lines from the data provided by an array in python using matplotlib. You can do it by specifying different columns of the array as the x and y-axis parameters in the matplotlib.pyplot.plot() function. You can select columns by slicing of the array.

Let’s first prepare the data for the example. Create an array using the numpy.array() function. In the below example, a 2D list is passed to the numpy.array() function.

import numpy as np# Define data values in arrayarr = np.array([[7, 5, 3], [14, 12, 5], [21, 19, 11], [28, 21, 20], [35, 31, 15], [42, 27, 29], [49, 35, 31]])print(np.shape(arr), type(arr), arr, sep='\n')
Python Plot Multiple Lines Using Matplotlib - Python Guides (4)

Now, plot multiple lines representing the relationship of the 1st column with the other columns of the array.

import matplotlib.pyplot as plt# Plot a simple line chartplt.plot(arr[:, 0], arr[:, 1], 'g', label='Line y')# Plot another line on the same chart/graphplt.plot(arr[:, 0], arr[:, 2], 'r', label='Line z')plt.legend()plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (5)

Read: What is NumPy

Python plot multiple lines from dataframe

You can plot multiple lines from the data provided by a Dataframe in python using matplotlib. You can do it by specifying different columns of the dataframe as the x and y-axis parameters in the matplotlib.pyplot.plot() function. You can select columns by slicing the dataframe.

Let’s prepare the data for the example. Create a dataframe using the pandas.DataFrame() function of pandas library. In the below example, a 2D list is passed to the pandas.DataFrame() function, and column names has been renamed to ‘x’, ‘y’, ‘z’.

import pandas as pdimport numpy as np# Define data values by creating a Dataframe using a n-dimensional listdf = pd.DataFrame([[7, 5, 3], [14, 12, 5], [21, 19, 11], [28, 21, 20], [35, 31, 15], [42, 27, 29], [49, 35, 31]])df.rename(columns={0: 'x', 1: 'y', 2: 'z'}, inplace=True)print(np.shape(df), type(df), df, sep='\n')
Python Plot Multiple Lines Using Matplotlib - Python Guides (6)

Now, plot multiple lines using the matplotlib.pyplot.plot() function.

import matplotlib.pyplot as plt# Plot a simple line chartplt.plot(df['x'], df['y'], color='g', label='Line y')# Plot another line on the same chart/graphplt.plot(df['x'], df['z'], color='r', label='Line z')plt.legend()plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (7)

Read: Python NumPy Array

Python plot multiple lines for loop

If there is a case where, there are several lines that have to be plotted on the same graph from a data source (array, Dataframe, CSV file, etc.), then it becomes time-consuming to separately plot the lines using matplotlib.pyplot.plot() function.

(Video) How to Plot Multiple Lines in Matplotlib Python

So, in such cases, you can use a for loop to plot the number of lines by using the matplotlib.pyplotlib.plot() function only once inside the loop, where x and y-axis parameters are not fixed but dependent on the loop counter.

Let’s prepare the data for the example, here a Dataframe is created with 4 columns and 7 rows.

import pandas as pdimport numpy as np# Define data values by creating a Dataframe using a n-dimensional listdf = pd.DataFrame([[7, 5, 3, 7], [14, 12, 5, 14], [21, 19, 11, 21], [28, 21, 20, 28], [35, 31, 15, 35], [42, 27, 29, 42], [49, 35, 31, 49]])df.rename(columns={0: 'x', 1: 'y', 2: 'z', 3: 'p'}, inplace=True)print(np.shape(df), type(df), df, sep='\n')
Python Plot Multiple Lines Using Matplotlib - Python Guides (8)

In the code below, the loop counter iterates over the column list of the Dataframe df. And 3 lines are plotted on the graph representing the relationship of the 1st column with the other 3 columns of the Dataframe.

import matplotlib.pyplot as pltfor col in df.columns: if not col == 'x': plt.plot(df['x'], df[col], label='Line '+col)plt.legend()plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (9)

Read: Matplotlib best fit line

Python plot multiple lines with different y axis

There are some cases where the values of different data to be plotted on the same graph differ hugely and the line with smaller data values doesn’t show its actual trend as the graph sets the scale of the bigger data.

To resolve this issue you can use different scales for the different lines and you can do it by using twinx() function of the axes of the figure, which is one of the two objects returned by the matplotlib.pyplot.subplots() function.

Let’s make the concept more clear by practicing a simple example:

First, prepare data for the example. Create a Dataframe using a dictionary in python containing the population density (per kmsq) and area 100kmsq of some of 20 countries.

import pandas as pd# Let's create a Dataframe using listscountries = ['Monaco', 'Singapore', 'Gibraltar', 'Bahrain', 'Malta', 'Maldives', 'Bermuda', 'Sint Maarten', 'Saint Martin', 'Guernsey', 'Vatican City', 'Jersey', 'Palestine', 'Mayotte', 'Lebnon', 'Barbados', 'Saint Martin', 'Taiwan', 'Mauritius', 'San Marino']area = [2, 106, 6, 97, 76, 80, 53, 34, 24, 13, 0.49, 86, 94, 16, 17, 3, 2.1, 1.8, 8, 14]pop_density = [19341, 8041, 5620, 2046, 1390, 1719, 1181, 1261, 1254, 2706, 1124.5, 1129, 1108, 1186, 1056, 1067, 1054, 1052, 944, 954]# Now, create a pandas dataframe using above listsdf_pop_density = pd.DataFrame( {'Country' : countries, 'Area(100kmsq)' : area, 'Population Density(/kmsq)' : pop_density})df_pop_density
Python Plot Multiple Lines Using Matplotlib - Python Guides (10)

Let’s plot the data conventionally without separate scaling for the lines. You can see that the Area line is not showing any identical trend with the data as the scale of the Area is very small comparatively from the Population Density.

import matplotlib.pyplot as plt# Creating figure and axis objects using subplots()fig, ax = plt.subplots(figsize=[9, 7])ax.plot(df_pop_density['Country'], df_pop_density['Area(100kmsq)'], marker='o', linewidth=2, label='Area')ax.plot(df_pop_density['Country'], df_pop_density['Population Density(/kmsq)'], marker='o', linewidth=2, linewidth=2, label='Population Density')plt.xticks(rotation=60)ax.set_xlabel('Countries')ax.set_ylabel('Area / Population Density')plt.legend()plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (11)

Now, let’s plot the lines with different y-axis having different scales using the twinx() function of the axes. You can also set the color and fontsize of the different y-axis labels. Now, you can see some identical trend of all the lines with the data.

# Creating figure and axis objects using subplots()fig, ax = plt.subplots(figsize=[9, 7])# Plotting the firts line with ax axesax.plot(df_pop_density['Country'], df_pop_density['Area(100kmsq)'], color='b', linewidth=2, marker='o')plt.xticks(rotation=60)ax.set_xlabel('Countries', fontsize=15)ax.set_ylabel('Area', color='blue', fontsize=15)# Create a twin axes ax2 using twinx() functionax2 = ax.twinx()# Now, plot the second line with ax2 axesax2.plot(df_pop_density['Country'], df_pop_density['Population Density(/kmsq)'], color='orange', linewidth=2, marker='o')ax2.set_ylabel('Population Density', color='orange', fontsize=15)plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (12)

Read: Matplotlib subplot tutorial

Python plot multiple lines time series

Time series is the collection of data values listed or indexed in order of time. It is the data taken at some successive interval of time like stock data, company’s sales data, climate data, etc., This type of data is commonly used and needed for the analysis purpose.

You can plot multiple lines showing trends of different parameters in a time series data in python using matplotlib.

Let’s import a dataset showing the sales details of a company over 8 years ( 2010 to 2017), you can use any time-series data set.

After importing the dataset, convert the date-time column (Here, ‘Date’) to the datestamp data type and sort it in ascending order by the ‘Date’ column. Set the ‘Date’ column as the index to make the data easier to plot.

import pandas as pd# Importing the dataset using the pandas into Dataframesales = pd.read_csv('./Data/Sales_records.csv')print(sales.head(), end='\n\n')# Converting the Date column to the datestamp typesales['Date'] = pd.to_datetime(sales['Date'])# Sorting data in ascending order by the datesales = sales.sort_values(by='Date')# Now, setting the Date column as the index of the dataframesales.set_index('Date', inplace=True)# Print the new dataframe and its summaryprint(sales.head(), sales.describe(), sep='\n\n')
Python Plot Multiple Lines Using Matplotlib - Python Guides (13)

You can plot the time series data with indexed datetime by either of the two methods given below.

By using the matplotlib.pyplot.plot() function in a loop or by directly plotting the graph with multiple lines from indexed time series data using the plot() function in the pandas.DataFrame.

In the code below, the value of the ‘figure.figsize’ parameter in rcParams parameter list is set to (15, 9) to set the figure size global to avoid setting it again and again in different graphs. You can follow any of the two methods given below:

import matplotlib.pyplot as plt# setting the graph size globallyplt.rcParams['figure.figsize'] = (15, 9)# No need of this statement for each graph: plt.figure(figsize=[15, 9])for col in sales.columns: plt.plot(sales[col], linewidth=2, label=col)plt.xlabel('Date', fontsize=20)plt.ylabel('Sales', fontsize=20)plt.xticks(fontsize=18)plt.yticks(fontsize=18)plt.legend(fontsize=18)# plt.set_cmap('Paired') # You can set the colormap to the graphplt.show()# OR You can also plot a timeseries data by the following methodsales.plot(colormap='Paired', linewidth=2, fontsize=18)plt.xlabel('Date', fontsize=20)plt.ylabel('Sales', fontsize=20)plt.legend(fontsize=18)plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (14)

Read: Matplotlib plot bar chart

Python plot multiple lines in 3D

You can plot multiple lines in 3D in python using matplotlib and by importing the mplot3d submodulefrom the modulempl_toolkits, an external toolkit for matplotlib in python used to plot the multi-vectors of geometric algebra.

Let’s do a simple example to understand the concept clearly. First, import the mplot3d submodule then set the projection in matplotlib.axes as ‘3d’.

Prepare some sample data, and then plot the data in the graph using matplotlib.pyplot.plot() as same as done in plotting multiple lines in 2d.

# Importing packagesimport matplotlib.pyplot as pltimport numpy as npfrom mpl_toolkits import mplot3dplt.axes(projection='3d')z = np.linspace(0, 1, 100)x1 = 3.7 * zy1 = 0.6 * x1 + 3x2 = 0.5 * zy2 = 0.6 * x2 + 2x3 = 0.8 * zy3 = 2.1 * x3plt.plot(x1, y1, z, 'r', linewidth=2, label='Line 1')plt.plot(x2, y2, z, 'g', linewidth=2, label='Line 2')plt.plot(x3, y3, z, 'b', linewidth=2, label='Line 3')plt.title('Plot multiple lines in 3D')plt.legend()plt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (15)

Read: Matplotlib time series plot

Matplotlib plot multiple lines with same color

In matplotlib, you can specify the color of the lines in the line charts. For this, you have to specify the value of the color parameter in the plot() function of the matplotlib.pyplot module.

(Video) Introduction to Line Plot Graphs with matplotlib Python

In Python, we have a wide range of hues i.e. colors. You can define the color by name, code, or hex code enclosed by quotations.

The color parameter can be specified as a keyword argument (e.g., color=’k’ –> means blackcolor; color=’blue’; color=’#DC143C’ –> means crimsoncolor) or as a positional argument (e.g., ‘r’ –> means redcolor; ‘g’ –> means greencolor).

Let’s have a look at examples where we specify the same colors for multiple lines:

Example #1

Here we plot multiple lines having the same color using positional argument.

# Importing packagesimport matplotlib.pyplot as pltimport numpy as np# Define data valuesx = range(3, 13)y1 = np.random.randn(10)y2 = np.random.randn(10)+range(3, 13)y3 = np.random.randn(10)+range(21,31)# Plot 1st lineplt.plot(x, y1, 'r', linestyle= 'dashed')# Plot 2nd lineplt.plot(x, y2, 'r')# Plot 3rd lineplt.plot(x, y3, 'r', linestyle = 'dotted')# Displayplt.show()
  • Import matplotlib.pyplot module for data visualization.
  • Import numpy module to define data coordinates.
  • To define data coordinates, use the range(), random.randn() functions.
  • To plot the line chart, use the plot() function.
  • To set different styles for lines, use linestyle parameter.
  • To set the same color to multiple lines, use positional arguments such as ‘r’, ‘g’.
Python Plot Multiple Lines Using Matplotlib - Python Guides (16)

Example #2

Here we plot multiple lines having the same color using hex code.

# Import Librariesimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.random.randint(low = 0, high = 60, size = 50)y = np.random.randint(low = -15, high = 80, size = 50)# Plotplt.plot(x, color='#EE1289', label='Line 1')plt.plot(y, color='#EE1289', linestyle = ':', label='Line 2')# Legendplt.legend()# Displayplt.show()
  • Import matplotlib.pyplot module for data visualization.
  • Import numpy module to define data coordinates.
  • To define data coordinates, use random.randint() functions and set its lowest, highest value and size also.
  • To plot the line chart, use the plot() function.
  • To set different styles for lines, use linestyle parameter.
  • To set the same color to multiple lines, use hex code.
  • To add a legend to the plot, pass label parameter to plot() function, and also use legend() function.
Python Plot Multiple Lines Using Matplotlib - Python Guides (17)

Example #3

Here we plot multiple lines having the same color using keyword argument.

# Import Librariesimport matplotlib.pyplot as plt# Define Datax = [1, 2, 3]y1 = [2, 3, 4]y2 = [5, 6, 7]y3 = [1, 2, 3]# Plotplt.plot(x, y1, color = 'g')plt.plot(x, y2, color = 'g')plt.plot(x, y3, color = 'g')# Displayplt.show()
  • Import matplotlib.pyplot library.
  • Next, define data coordinates.
  • To plot the line chart, use the plot() function.
  • To set the same color to multiple line charts, use keyword argument color and specify the color name in short form.
Python Plot Multiple Lines Using Matplotlib - Python Guides (18)

Example #4

In matplotlib, using the keyword argument, we plot multiple lines of the same color.

# Import Librariesimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0,6,0.2)y1 = np.sin(x)y2 = np.cos(x)# Plotplt.plot(x, y1, color ='slategray')plt.plot(x, y2, color = 'slategray')# Displayplt.show()
  • Import matplotlib.pyplot library.
  • Import numpy package.
  • Next, define data coordinates using arange(), sin() and cos() functions.
  • To plot the line chart, use the plot() function.
  • To set the same color to multiple line charts, use keyword argument color and specify the color name.
Python Plot Multiple Lines Using Matplotlib - Python Guides (19)

Read: Matplotlib update plot in loop

Matplotlib plot title multiple lines

Here we’ll learn to add a title to multiple lines chart using matplotlib with the help of examples. In matplotlib, we have two ways to add a title to a plot.

The first way is when we want to add a single or main title to the plots or subplots, then we use suptitle() function of pyplot module. And the second way is when we want to add different titles to each plot or subplot, then we use the title() function of pyplot module.

Let’s see different examples:

Example #1

In this example, we’ll learn to add the main title to multiple lines plot.

# Import Librariesimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(20)y1 = x+8y2 = 2*x+8y3 = 4*x+8y4 = 6*x+8y5 = 8*x+8# Colorscolors=['lightcoral', 'yellow', 'lime', 'slategray', 'pink']plt.gca().set_prop_cycle(color=colors)# Plotplt.plot(x, y1)plt.plot(x, y2)plt.plot(x, y3)plt.plot(x, y4)plt.plot(x, y5)# Main Titleplt.suptitle("Multiple Lines Plot", fontweight='bold')# Displayplt.show()
  • Import matplotlib.pyplot package for data visualization.
  • Import numpy package for data plotting.
  • To define data coordinates, use arange() function.
  • The matplotlib.axes.Axes.set_prop_cycle() method takes a list of colors to use in order as an argument.
  • To plot multiple line chart, use plot() function.
  • To add a main title to a plot, use suptitle() function.
Python Plot Multiple Lines Using Matplotlib - Python Guides (20)

Example #2

In this example, we’ll learn to add title to multiple lines plot.

# Import Librariesimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.linspace(0, 8, 100)y1 = 5*xy2 = np.power(x,2)y3 = np.exp(x/18)# Plotplt.plot(x, y1, color='coral')plt.plot(x, y2, color='lawngreen')plt.plot(x, y3)# Titleplt.title("Multiple Lines Plot", fontweight='bold')# Displayplt.show()
  • Firstly, import matplotlib.pyplot and numpy libraries.
  • To define data coordinates, use linspace(), power(), and exp() functions.
  • To plot a line, use plot() function of pyplot module.
  • To add a title to a plot, use title() function.
Python Plot Multiple Lines Using Matplotlib - Python Guides (21)

Example #3

In this example, we’ll add the title in multiple lines.

# Import Librariesimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0,10,0.2)y1 = np.sin(x)y2 = np.cos(x)# Plotplt.plot(x, y1)plt.plot(x, y2)# Multiple line titleplt.suptitle('Plot Multple Lines \n With Multiple Lines Titles', fontweight='bold')# Displayplt.show()
  • Import matplotlib.pyplot library.
  • Import numpy library.
  • Next, define data coordinates using arange(), sin(), and cos() functions.
  • To plot a line chart, use plot() function.
  • To add a title in multiple lines, use suptitle() function with new line character.
Python Plot Multiple Lines Using Matplotlib - Python Guides (22)

Read: Matplotlib Pie Chart Tutorial

Matplotlib plot multiple lines in subplot

In matplotlib, to plot a subplot, use the subplot() function. The subplot() function requires three arguments, each one describes the figure’s arrangement.

The first and second arguments, respectively, indicate rows and columns in the layout. The current plot’s index is represented by the third argument.

Let’s see examples of a subplot having multiple lines:

(Video) Matplotlib Plot Multiple Lines | Plot Multiple Lines in Matplotlib in Python P-2|

Example #1

In the above example, we use the subplot() function to create subplots.

# Import Librariesimport matplotlib.pyplot as pltimport numpy as np# Set figure sizeplt.figure(figsize=(8,6))# plot 1:plt.subplot(1, 2, 1)# Datax = np.random.randint(low = 0, high = 150, size = 30)y = np.random.randint(low = 10, high = 50, size = 30)# Plottingplt.plot(x)plt.plot(y)# plot 2:plt.subplot(1, 2, 2 )# Datax = [1, 2, 3]y1 = [2, 3, 4]y2 = [5, 6, 7]# Plottingplt.plot(x,y1)plt.plot(x,y2)# Displayplt.show()
  • Import matplotlib.pyplot and numpy packages.
  • To set figure size use figsize and set width and height.
  • To plot subplot, use subplot() function with rows, columns and index numbers.
  • To define data coordinates, use random.randint() function.
  • To plot a line chart, use plot() function.
Python Plot Multiple Lines Using Matplotlib - Python Guides (23)

Example #2

Let’s see one more example, to create subplots with multiple lines.

# Import Librariesimport matplotlib.pyplot as pltimport numpy as np# Set figure sizeplt.figure(figsize=(8,6))# plot 1:plt.subplot(1, 2, 1)# Datax = np.linspace(0, 8, 100)y1 = np.exp(x/18)y2 = 5*x# Plottingplt.plot(x, y1)plt.plot(x, y2)# plot 2:plt.subplot(1, 2, 2 )# Datax = np.arange(0,10,0.2)y1 = np.sin(x)y2 = np.cos(x)# Plottingplt.plot(x,y1)plt.plot(x,y2)# Displayplt.show()
  • Here we use linspace(), exp(), arange(), sin(), and cos() functions to define data coordinates to plot subplot.
  • To plot a line chart, use plot() functions.
Python Plot Multiple Lines Using Matplotlib - Python Guides (24)

Read: Matplotlib scatter plot color

Matplotlib plot multiple lines different length

In Matplotlib, we’ll learn to plot multiple lines having different lengths with the help of examples.

Let’s see examples related to this:

Example #1

In this example, we’ll use the axhline() method to plot multiple lines with different lengths and with the same color.

# Import libraryimport matplotlib.pyplot as plt # line 1plt.axhline (y = 2) # line 2 plt.axhline (y = 3, xmax =0.4)# line 3plt.axhline (y = 4, xmin = 0.4, xmax =0.8)# line 4plt.axhline (y = 5, xmin =0.25, xmax =0.65)# Line 5plt.axhline (y = 6, xmin =0.6, xmax =0.8) # Displayplt.show()
  • Import matplotlib.pyplot library.
  • Next, we use the axhline() method to plot multiple lines.
  • To set different lengths of lines we pass xmin and xmax parameters to the method.
  • To get lines with the same color, we can’t specify the color parameter. If you, want different color lines specify color parameter also.
Python Plot Multiple Lines Using Matplotlib - Python Guides (25)

Example #2

In this example, we’ll use the hlines() method to plot multiple lines with different lengths and with different colors.

# Import libraryimport matplotlib.pyplot as plt # line 1plt.hlines (y= 2, xmin= 0.1, xmax= 0.35, color='c') # line 2 plt.hlines (y= 4, xmin = 0.1, xmax = 0.55, color='m', linestyle = 'dotted')# line 3plt.hlines (y = 6, xmin = 0.1, xmax = 0.75, color='orange', linestyle = 'dashed')# line 4plt.hlines (y = 8, xmin =0.1, xmax =0.9, color='red') # Displayplt.show()
  • Import matplotlib.pyplot library.
  • Next, we use the hlines() method to plot multiple lines.
  • To set different lengths of lines we pass xmin and xmax parameters to the method.
  • If you, want different color lines specify color parameter also.
Python Plot Multiple Lines Using Matplotlib - Python Guides (26)

Example #3

In this example, we’ll use the axvline() method to plot multiple lines with different lengths.

# Import libraryimport matplotlib.pyplot as plt # line 1plt.axvline(x = 5, color = 'b') # line 2 plt.axvline(x = 3, ymin = 0.2, ymax = 0.8, color='red')# line 3plt.axvline(x = 3.75, ymin = 0.2, ymax = 1, color='lightgreen')# line 4plt.axvline(x = 4.50, ymin = 0, ymax = 0.65, color='m') # Displayplt.show()
  • Import matplotlib.pyplot library.
  • Next, we use the axvline() method to plot multiple lines.
  • To set different lengths of lines we pass ymin and ymax parameters to the method.
  • If you, want different color lines specify color parameter also.
Python Plot Multiple Lines Using Matplotlib - Python Guides (27)

Example #4

In this example, we’ll use the vlines() method to plot multiple lines with different lengths.

# Import libraryimport matplotlib.pyplot as plt # Vertical line 1plt.vlines(x = 5, ymin = 0.75, ymax = 2, color = 'black') # Vertical line 2plt.vlines (x = 8, ymin = 0.50, ymax = 1.5, color='red')# Vertical line 3plt.vlines (x = [1, 2] , ymin = 0.2, ymax = 0.6, color = 'orange') # Vertical line 4plt.vlines (x = 10, ymin = 0.2, ymax = 2, color='yellow') # Displayplt.show()
  • Here we use the axvline() method to plot multiple lines.
  • To set different lengths of lines we pass ymin and ymax parameters to the method.
Python Plot Multiple Lines Using Matplotlib - Python Guides (28)

Example #5

In this example, we’ll use the array() function of numpy to plot multiple lines with different lengths.

# Import Librariesimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.array([2, 4, 6, 8, 10, 12])y = np.array([3, 6, 9])# Plotplt.plot(x)plt.plot(y)# Displayplt.show()
  • Firstly, import matplotlib.pyplot, and numpy libraries.
  • Next, define data coordinates using the array() method of numpy. Here we define lines of different lengths.
  • To plot a line chart, use the plot() method.
Python Plot Multiple Lines Using Matplotlib - Python Guides (29)

Example #6

In this example, we use the range() function to plot multiple lines with different lengths.

# Import libraryimport matplotlib.pyplot as plt# Create subplotfig, ax = plt.subplots()# Define Datax = range(2012,2022)y = [10, 11, 10.5, 15, 16, 19, 14.5, 12, 13, 20]x1 = range(2016, 2022)y1 = [11.5, 15.5, 15, 16, 20, 11]# Plot ax.plot(x, y, color= '#CD1076')ax.plot(x1,y1, color = 'orange')# Showplt.show()
  • Import matplotlib.pyplot library.
  • To create subplot, use subplots() function.
  • Next, define data coordinates using range() function to get multiple lines with different lengths.
  • To plot a line chart, use the plot() function.
Python Plot Multiple Lines Using Matplotlib - Python Guides (30)

Read: Matplotlib Plot NumPy Array

Matplotlib plot multiple lines seaborn

In matplotlib, you can draw multiple lines using the seaborn lineplot() function.

The following is the syntax:

sns.lineplot(x, y, hue)

Here x, y, and hue represent x-axis coordinate, y-axis coordinate, and color respectively.

Let’s see examples related to this:

(Video) Python - Matplotlib Tutorial for Beginners

Example #1

# Import Librariesimport seaborn as snsimport pandas as pd import matplotlib.pyplot as plt# Define Datadays = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]max_temp = [36.6, 37, 37.7, 13, 15.6, 46.8, 50, 22, 31, 26, 18, 42, 28, 26, 12]min_temp = [12, 8, 18, 12, 11, 4, 3, 19, 20, 10, 12, 9, 14, 19, 16]# Dataframetemp_df = pd.DataFrame({"days":days, "max_temp":max_temp, "min_temp":min_temp})# Printtemp_df
  • Firstly, import necessary libraries such as seaborn, matplotlib.pyplot, and pandas.
  • Next, define data.
  • To create data frame, use DataFrame() function of pandas.
Python Plot Multiple Lines Using Matplotlib - Python Guides (31)
# Plot seaborn sns.lineplot(x = "days", y = "max_temp", data=temp_df,)sns.lineplot(x = "days", y = "min_temp", data=temp_df,)# Showplt.show()
  • To plot multiple line chart using seaborn package, use lineplot() function.
  • To display the graph, use show() function.
Python Plot Multiple Lines Using Matplotlib - Python Guides (32)

Example #2

# Import Librariesimport seaborn as snsimport numpy as npimport matplotlib.pyplot as plt# Define Datax = np.linspace (1,10,2)y = x * 2z = np.exp(x)# Seaborn Plotsns.lineplot(x = x, y = y)sns.lineplot(x = x, y = z)# Showplt.show()
  • Import libraries such as seaborn, numpy, and matplotlib.pyplot.
  • To define data coordinates, use linspace(), exp() functions of numpy.
  • To plot seaborn line plot, use lineplot() function.
  • To display the graph, use show() function.
Python Plot Multiple Lines Using Matplotlib - Python Guides (33)

Example #3

# Import Librariesimport matplotlib.pyplot as pltimport numpy as npimport seaborn as sns# Set stylesns.set_style("darkgrid")# Define Datax = np.arange(0,20,0.2)y1 = np.cos(x)y2 = np.sin(2*x)# Plotsns.lineplot(x = x, y = y1)sns.lineplot(x = x, y = y2)# Displayplt.show()
  • Import necessary libraries such as, matplotlib.pyplot, numpy, and seaborn.
  • Set style of plot, use set_style() method and set it to darkgrid.
  • To define data coordinates, use arange(), cos(), and sin() functions.
  • To plot multiple lines, use lineplot() function.
  • To visualize the plot, use show() function.
Python Plot Multiple Lines Using Matplotlib - Python Guides (34)

Read: Matplotlib set_xticklabels

Matplotlib plot multiple lines from csv files

Here we’ll learn how to plot multiple lines from CSV files using matplotlib.

To download the dataset click Max_Temp:

To understand the concept more clearly, lets see different examples:

  • Import necessary libraries such as pandas and matplotlib.pyplot.
  • Next, read the csv file using read_csv() function of pandas.
  • To view the csv file, print it.

Source Code:

# Import Librariesimport pandas as pd import matplotlib.pyplot as plt # Read CSVdata= pd.read_csv('Max_Temp.csv')# Print data
Python Plot Multiple Lines Using Matplotlib - Python Guides (35)
  • Next, we convert the CSV file to the panda’s data frame, using theDataFrame()function.
  • If you, want to view the data frame print it.
# Convert data framedf=pd.DataFrame(data)# Printdf
Python Plot Multiple Lines Using Matplotlib - Python Guides (36)
  • By usingiloc()function, initialize the list to select the rows and columns by position from pandas Dataframe.
# Initilaize list days = list(df.iloc[:,0])city_1 = list(df.iloc[:,1])city_2 = list(df.iloc[:,2])city_3 = list(df.iloc[:,3])city_4 = list(df.iloc[:,4])

Example #1

  • Now, set the figure size by usingfigsize()function
  • To plot multiple lines chart , use theplot()function and pass the data coordinates.
  • To set a marker, passmarkeras a parameter.
  • To visualize the graph, use theshow()function.
# Set Figure Sizeplt.figure(figsize=(8,6))# Plotplt.plot(days, city_4, marker='o')plt.plot(days, city_2, marker='o')# Displayplt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (37)

Example #2

In this example, we draw three multiple lines plots.

# Set Figure Sizeplt.figure(figsize=(8,6))# Plotplt.plot(days, city_4, marker='o')plt.plot(days, city_2, marker='o')plt.plot(days, city_1, marker='o')# Displayplt.show()
Python Plot Multiple Lines Using Matplotlib - Python Guides (38)

You may also like to read the following articles.

  • What is matplotlib inline
  • Matplotlib bar chart labels
  • Put legend outside plot matplotlib

In this tutorial, we have discussed, How to plot multiple lines using matplotlib in Python, and we have also covered the following topics:

  • Python plot multiple lines on same graph
  • Python plot multiple lines of different color
  • Python plot multiple lines with legend
  • Python plot multiple lines from array
  • Python plot multiple lines from dataframe
  • Python plot multiple lines for loop
  • Python plot multiple lines with different y axis
  • Python plot multiple lines time series
  • Python plot multiple lines in 3D
  • Matplotlib plot multiple lines with same color.
  • Matplotlib plot title multiple lines
  • Matplotlib plot multiple lines in subplot
  • Matplotlib plot multiple lines different length
  • Matplotlib plot multiple lines seaborn
  • Matplotlib plot multiple lines from csv files

Python Plot Multiple Lines Using Matplotlib - Python Guides (39)

Bijay Kumar

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

enjoysharepoint.com/

(Video) Data Analysis Using Pandas DataFrame & Matplotlib 14 - Plotting a Line Chart

Videos

1. Matplotlib Tutorial (Part 10): Subplots
(Corey Schafer)
2. Matplotlib Tutorial (Part 1): Creating and Customizing Our First Plots
(Corey Schafer)
3. HOW TO PLOT MULTIPLE GRAPHS IN PYTHON | PYTHON TUTORIAL FOR BEGINNERS
(ITS InfoTechSkills)
4. Matplotlib Charts With Tkinter - Python Tkinter GUI Tutorial #27
(Codemy.com)
5. Animating Plots In Python Using MatplotLib [Python Tutorial]
(CodingLikeMad)
6. What is Matplotlib inline in Python
(TSInfo Technologies)
Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated: 04/02/2023

Views: 5629

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.