# Python plot multiple lines using Matplotlib

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

## 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.

## 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()``````

## 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()``````

## 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()``````

## Python plot multiple lines for loop

If there is a case where, there are several lines that have to be plot 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()``````

## 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()``````

## 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

# 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

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()``````

## 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()``````