In this Python tutorial, we will discuss, How to plot multiple lines using matplotlib in 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
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 packages
import matplotlib.pyplot as plt
# Define data values
x = [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 chart
plt.plot(x, y)
# Plot another line on the same chart/graph
plt.plot(x, z)
plt.show()
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 packages
import matplotlib.pyplot as plt
# Define data values
x = [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 chart
plt.plot(x, y, 'c')
# Plot another line on the same chart/graph
plt.plot(x, z, 'y')
plt.show()
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 packages
import matplotlib.pyplot as plt
# Define data values
x = [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 chart
plt.plot(x, y, 'g', label='Line y')
# Plot another line on the same chart/graph
plt.plot(x, z, 'r', label='Line z')
plt.legend()
plt.show()
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 array
arr = 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')
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 chart
plt.plot(arr[:, 0], arr[:, 1], 'g', label='Line y')
# Plot another line on the same chart/graph
plt.plot(arr[:, 0], arr[:, 2], 'r', label='Line z')
plt.legend()
plt.show()
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 pd
import numpy as np
# Define data values by creating a Dataframe using a n-dimensional list
df = 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')
Now, plot multiple lines using the matplotlib.pyplot.plot() function.
import matplotlib.pyplot as plt
# Plot a simple line chart
plt.plot(df['x'], df['y'], color='g', label='Line y')
# Plot another line on the same chart/graph
plt.plot(df['x'], df['z'], color='r', label='Line z')
plt.legend()
plt.show()
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.
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 pd
import numpy as np
# Define data values by creating a Dataframe using a n-dimensional list
df = 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')
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 plt
for col in df.columns:
if not col == 'x':
plt.plot(df['x'], df[col], label='Line '+col)
plt.legend()
plt.show()
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 lists
countries = ['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 lists
df_pop_density = pd.DataFrame(
{'Country' : countries, 'Area(100kmsq)' : area,
'Population Density(/kmsq)' : pop_density})
df_pop_density
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()
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 axes
ax.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() function
ax2 = ax.twinx()
# Now, plot the second line with ax2 axes
ax2.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()
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 Dataframe
sales = pd.read_csv('./Data/Sales_records.csv')
print(sales.head(), end='\n\n')
# Converting the Date column to the datestamp type
sales['Date'] = pd.to_datetime(sales['Date'])
# Sorting data in ascending order by the date
sales = sales.sort_values(by='Date')
# Now, setting the Date column as the index of the dataframe
sales.set_index('Date', inplace=True)
# Print the new dataframe and its summary
print(sales.head(), sales.describe(), sep='\n\n')
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 globally
plt.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 graph
plt.show()
# OR You can also plot a timeseries data by the following method
sales.plot(colormap='Paired', linewidth=2, fontsize=18)
plt.xlabel('Date', fontsize=20)
plt.ylabel('Sales', fontsize=20)
plt.legend(fontsize=18)
plt.show()
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 submodule from the module mpl_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 packages
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
plt.axes(projection='3d')
z = np.linspace(0, 1, 100)
x1 = 3.7 * z
y1 = 0.6 * x1 + 3
x2 = 0.5 * z
y2 = 0.6 * x2 + 2
x3 = 0.8 * z
y3 = 2.1 * x3
plt.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()
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.
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 black color; color=’blue’; color=’#DC143C’ –> means crimson color) or as a positional argument (e.g., ‘r’ –> means red color; ‘g’ –> means green color).
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 packages
import matplotlib.pyplot as plt
import numpy as np
# Define data values
x = 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 line
plt.plot(x, y1, 'r', linestyle= 'dashed')
# Plot 2nd line
plt.plot(x, y2, 'r')
# Plot 3rd line
plt.plot(x, y3, 'r', linestyle = 'dotted')
# Display
plt.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’.
Example #2
Here we plot multiple lines having the same color using hex code.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.random.randint(low = 0, high = 60, size = 50)
y = np.random.randint(low = -15, high = 80, size = 50)
# Plot
plt.plot(x, color='#EE1289', label='Line 1')
plt.plot(y, color='#EE1289', linestyle = ':', label='Line 2')
# Legend
plt.legend()
# Display
plt.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.
Example #3
Here we plot multiple lines having the same color using keyword argument.
# Import Libraries
import matplotlib.pyplot as plt
# Define Data
x = [1, 2, 3]
y1 = [2, 3, 4]
y2 = [5, 6, 7]
y3 = [1, 2, 3]
# Plot
plt.plot(x, y1, color = 'g')
plt.plot(x, y2, color = 'g')
plt.plot(x, y3, color = 'g')
# Display
plt.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.
Example #4
In matplotlib, using the keyword argument, we plot multiple lines of the same color.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.arange(0,6,0.2)
y1 = np.sin(x)
y2 = np.cos(x)
# Plot
plt.plot(x, y1, color ='slategray')
plt.plot(x, y2, color = 'slategray')
# Display
plt.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.
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 Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.arange(20)
y1 = x+8
y2 = 2*x+8
y3 = 4*x+8
y4 = 6*x+8
y5 = 8*x+8
# Colors
colors=['lightcoral', 'yellow', 'lime', 'slategray', 'pink']
plt.gca().set_prop_cycle(color=colors)
# Plot
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.plot(x, y4)
plt.plot(x, y5)
# Main Title
plt.suptitle("Multiple Lines Plot", fontweight='bold')
# Display
plt.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.
Example #2
In this example, we’ll learn to add title to multiple lines plot.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.linspace(0, 8, 100)
y1 = 5*x
y2 = np.power(x,2)
y3 = np.exp(x/18)
# Plot
plt.plot(x, y1, color='coral')
plt.plot(x, y2, color='lawngreen')
plt.plot(x, y3)
# Title
plt.title("Multiple Lines Plot", fontweight='bold')
# Display
plt.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.
Example #3
In this example, we’ll add the title in multiple lines.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.arange(0,10,0.2)
y1 = np.sin(x)
y2 = np.cos(x)
# Plot
plt.plot(x, y1)
plt.plot(x, y2)
# Multiple line title
plt.suptitle('Plot Multple Lines \n With Multiple Lines
Titles', fontweight='bold')
# Display
plt.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.
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:
Example #1
In the above example, we use the subplot() function to create subplots.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.figure(figsize=(8,6))
# plot 1:
plt.subplot(1, 2, 1)
# Data
x = np.random.randint(low = 0, high = 150, size = 30)
y = np.random.randint(low = 10, high = 50, size = 30)
# Plotting
plt.plot(x)
plt.plot(y)
# plot 2:
plt.subplot(1, 2, 2 )
# Data
x = [1, 2, 3]
y1 = [2, 3, 4]
y2 = [5, 6, 7]
# Plotting
plt.plot(x,y1)
plt.plot(x,y2)
# Display
plt.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.
Example #2
Let’s see one more example, to create subplots with multiple lines.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.figure(figsize=(8,6))
# plot 1:
plt.subplot(1, 2, 1)
# Data
x = np.linspace(0, 8, 100)
y1 = np.exp(x/18)
y2 = 5*x
# Plotting
plt.plot(x, y1)
plt.plot(x, y2)
# plot 2:
plt.subplot(1, 2, 2 )
# Data
x = np.arange(0,10,0.2)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting
plt.plot(x,y1)
plt.plot(x,y2)
# Display
plt.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.
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 library
import matplotlib.pyplot as plt
# line 1
plt.axhline (y = 2)
# line 2
plt.axhline (y = 3, xmax =0.4)
# line 3
plt.axhline (y = 4, xmin = 0.4, xmax =0.8)
# line 4
plt.axhline (y = 5, xmin =0.25, xmax =0.65)
# Line 5
plt.axhline (y = 6, xmin =0.6, xmax =0.8)
# Display
plt.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.
Example #2
In this example, we’ll use the hlines() method to plot multiple lines with different lengths and with different colors.
# Import library
import matplotlib.pyplot as plt
# line 1
plt.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 3
plt.hlines (y = 6, xmin = 0.1, xmax = 0.75, color='orange',
linestyle = 'dashed')
# line 4
plt.hlines (y = 8, xmin =0.1, xmax =0.9, color='red')
# Display
plt.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.
Example #3
In this example, we’ll use the axvline() method to plot multiple lines with different lengths.
# Import library
import matplotlib.pyplot as plt
# line 1
plt.axvline(x = 5, color = 'b')
# line 2
plt.axvline(x = 3, ymin = 0.2, ymax = 0.8, color='red')
# line 3
plt.axvline(x = 3.75, ymin = 0.2, ymax = 1, color='lightgreen')
# line 4
plt.axvline(x = 4.50, ymin = 0, ymax = 0.65, color='m')
# Display
plt.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.
Example #4
In this example, we’ll use the vlines() method to plot multiple lines with different lengths.
# Import library
import matplotlib.pyplot as plt
# Vertical line 1
plt.vlines(x = 5, ymin = 0.75, ymax = 2, color = 'black')
# Vertical line 2
plt.vlines (x = 8, ymin = 0.50, ymax = 1.5, color='red')
# Vertical line 3
plt.vlines (x = [1, 2] , ymin = 0.2, ymax = 0.6,
color = 'orange')
# Vertical line 4
plt.vlines (x = 10, ymin = 0.2, ymax = 2, color='yellow')
# Display
plt.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.
Example #5
In this example, we’ll use the array() function of numpy to plot multiple lines with different lengths.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.array([2, 4, 6, 8, 10, 12])
y = np.array([3, 6, 9])
# Plot
plt.plot(x)
plt.plot(y)
# Display
plt.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.
Example #6
In this example, we use the range() function to plot multiple lines with different lengths.
# Import library
import matplotlib.pyplot as plt
# Create subplot
fig, ax = plt.subplots()
# Define Data
x = 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')
# Show
plt.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.
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:
Example #1
# Import Libraries
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# Define Data
days = [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]
# Dataframe
temp_df = pd.DataFrame({"days":days, "max_temp":max_temp,
"min_temp":min_temp})
# Print
temp_df
- Firstly, import necessary libraries such as seaborn, matplotlib.pyplot, and pandas.
- Next, define data.
- To create data frame, use DataFrame() function of pandas.
# Plot seaborn
sns.lineplot(x = "days", y = "max_temp", data=temp_df,)
sns.lineplot(x = "days", y = "min_temp", data=temp_df,)
# Show
plt.show()
- To plot multiple line chart using seaborn package, use lineplot() function.
- To display the graph, use show() function.
Example #2
# Import Libraries
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
# Define Data
x = np.linspace (1,10,2)
y = x * 2
z = np.exp(x)
# Seaborn Plot
sns.lineplot(x = x, y = y)
sns.lineplot(x = x, y = z)
# Show
plt.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.
Example #3
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# Set style
sns.set_style("darkgrid")
# Define Data
x = np.arange(0,20,0.2)
y1 = np.cos(x)
y2 = np.sin(2*x)
# Plot
sns.lineplot(x = x, y = y1)
sns.lineplot(x = x, y = y2)
# Display
plt.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.
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, let‘s 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 Libraries
import pandas as pd
import matplotlib.pyplot as plt
# Read CSV
data= pd.read_csv('Max_Temp.csv')
# Print
data
- Next, we convert the CSV file to the panda’s data frame, using the DataFrame() function.
- If you, want to view the data frame print it.
# Convert data frame
df=pd.DataFrame(data)
# Print
df
- By using iloc() 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 using figsize() function
- To plot multiple lines chart , use the plot() function and pass the data coordinates.
- To set a marker, pass marker as a parameter.
- To visualize the graph, use the show() function.
# Set Figure Size
plt.figure(figsize=(8,6))
# Plot
plt.plot(days, city_4, marker='o')
plt.plot(days, city_2, marker='o')
# Display
plt.show()
Example #2
In this example, we draw three multiple lines plots.
# Set Figure Size
plt.figure(figsize=(8,6))
# Plot
plt.plot(days, city_4, marker='o')
plt.plot(days, city_2, marker='o')
plt.plot(days, city_1, marker='o')
# Display
plt.show()
You may also like to read the following articles.
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
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.